const g_reminderFoxBundle = document.getElementById("reminderFox-bundle");  

//const REPEAT_LABEL_NONE =    g_reminderFoxBundle.getString("rf.add.columns.repeat.none");
const REPEAT_LABEL_NONE =    "";
const REPEAT_LABEL_YEARLY =    g_reminderFoxBundle.getString("rf.add.columns.repeat.yearly");
const REPEAT_LABEL_YEARLY_DAY =    g_reminderFoxBundle.getString("rf.add.columns.repeat.yearlyDay");
const REPEAT_LABEL_MONTHLY =    g_reminderFoxBundle.getString("rf.add.columns.repeat.monthly");
const REPEAT_LABEL_MONTHLY_DAY =    g_reminderFoxBundle.getString("rf.add.columns.repeat.monthlyDay");
const REPEAT_LABEL_WEEKLY =    g_reminderFoxBundle.getString("rf.add.columns.repeat.weekly");
const REPEAT_LABEL_DAILY =    g_reminderFoxBundle.getString("rf.add.columns.repeat.daily");


//const REMINDER_FOX_TIME_ALL_DAY_LABEL = g_reminderFoxBundle.getString("rf.add.time.allday");
const REMINDER_FOX_TIME_ALL_DAY_LABEL = "";

const REMINDER_FOX_AM =    g_reminderFoxBundle.getString("rf.add.time.AM");
const REMINDER_FOX_PM =    g_reminderFoxBundle.getString("rf.add.time.PM");
const REMINDER_FOX_TIME_DELIMITER=g_reminderFoxBundle.getString( "rf.add.time.delimiter");

 
// constants 
const REMINDER_ID_REF = "idRef";
const REMINDER_DATE_REF = "dateRef";

var g_modified = false;

var showSidebar = true;
var showFilters = false;

var selectCalendarSync = false;
var calendarReminderArray = null; // new Array(12);
var calendarTodoArray = null;

var lastSearchString = null;

var reminderFox_subscribedCalendars = { };

var useDefaultDate = true;
var dateVariableString = "";

var REPEAT_PREVIOUS_OCCURRENCES;
var REPEAT_UPCOMING_OCCURRENCES;

var SHOW_ALL_REMINDERS = false;
var HIDE_ALL_REMINDERS = false;
var HIDE_COMPLETED_ITEMS = false;
var reminderFoxTabDirtied = false;

var reminderFox_highlightTodayPreference = true;

var listSortMap = null;

// searchbar
var searchBarWaitTime = null;  
const SEARCHBAR_WAIT_DELAY = 600;

const searchItems 	= ["summary",			"categories",		"notes", "location", "ALL"];
const rmColumnLabels	= ["descColLabel",		"catColLabel",		"notesColLabel"];
const tdColumnLabels	= ["todoDescColLabel",	"todocatColLabel",	"todoNotesColLabel"];
const SEARCH_ITEMS_ALL_INDEX = 4;

//gW_focus
function selectFocus(element) {
	var str ="";
	if ((element == null)) {
		isReminderTabSelected() ? 
				document.getElementById("addReminderButton").focus()		
			:	document.getElementById("addTodoButton").focus();
	} else {
	   document.getElementById(element).focus(); 
	}
}

var lastRmSearchText ="";
var lastTodoSearchText = "";
var lastTodoTab = "";
var currentRmSearchItemValue = 0;
var currentTodoSearchItemValue=0;
	
function rmCheckMenuItem (menuNo){
/*	----------------------------- sets the selected menu item  by menuNo
*/
	var menuItems = document.getElementById('quick-search-menupopup')
		.getElementsByAttribute('value', '*');
		
	if (menuItems.length > 0)  {	
		for (var i=1; i< menuItems.length; i++) {
			menuItems[i].removeAttribute('checked');
	    }  	
	}  	
	menuItems[menuNo].setAttribute('checked', 'true');  

	var cLabel = document.getElementById('rmSearchText')
	cLabel.value = 	menuItems[menuNo].getAttribute('label');
	
	if ( isReminderTabSelected() ) {
		currentRmSearchItemValue = menuNo;
	}
	else {
		currentTodoSearchItemValue = menuNo;
	}
	//if ( isListFiltered() ) {  // always want to clear headers
		rmHighlightHeader(menuNo);
	//}
}

function rmHighlightHeader(menuNo) {
	/*  ------  'highligth the List-Column-Header'  ------ */	
	if ( isReminderTabSelected() ) {
		for (var i=0; i < rmColumnLabels.length; i++) {
			var colLabel = document.getElementById(rmColumnLabels[i]);
			if ( colLabel != null ) {
				colLabel.setAttribute( "style", "color:black; font-weight:normal");
			}
		}
		if ( isListFiltered() ) {
			if ( menuNo != SEARCH_ITEMS_ALL_INDEX ) { 
				var colLabel = document.getElementById(rmColumnLabels[menuNo])	
				if ( colLabel != null ) {
					colLabel.setAttribute( "style", "color:blue; font-weight:bold");
				}
			}
			else {
				// highlight them all 
				for (var i=0; i < rmColumnLabels.length; i++) {
					var colLabel = document.getElementById(rmColumnLabels[i]);
					if ( colLabel != null ) {
						colLabel.setAttribute( "style", "color:blue; font-weight:bold");
					}
				}
			
			}
		}
	}
	else {		
		for (var i=0; i < tdColumnLabels.length; i++) {
			var colLabel = document.getElementById(tdColumnLabels[i])	;
			if ( colLabel != null ) {
				colLabel.setAttribute( "style", "color:black; font-weight:normal");
			}
		}
		if ( isListFiltered() ) { 
			if ( menuNo != SEARCH_ITEMS_ALL_INDEX ) { 
				var colLabel = document.getElementById(tdColumnLabels[menuNo]);
				if ( colLabel != null ) {
					colLabel.setAttribute( "style", "color:blue; font-weight:bold");
				}
			}
			// highlight them all 
				for (var i=0; i < tdColumnLabels.length; i++) {
					var colLabel = document.getElementById(tdColumnLabels[i]);
					if ( colLabel != null ) {
						colLabel.setAttribute( "style", "color:blue; font-weight:bold");
					}
				}
		}
	}
}

function rmOnInputQSearch(event) {
/*	-------------------------- this is called with every Input action 
*/
	event.style.color="blue";  
}		


/**
 * The quicksearch response is split between onSearchKeyDown and onSearchKeyUp because this logic
 * is tied to a timed function that sets the focus on the quicksearch bar after a period of time.
 * This split is required for Japanese input using Input Method Editor(IME), where they enter some characters and 
 * then need to select the converted Japanese text from the IME.  If the quicksearch textbox steals the focus 
 * before that is completed, it screws up the input conversion.  As such, we put the logic in the onKeyUp event
 * instead, which is only called after the IME is finished.  
 */
function rmOnSearchKeyPress(event)	{
	if (event.keyCode==9) {
		 return;		/* break the focus */
	}
	
	var qs_button = document.getElementById('quick-search-clearbutton');
	if (qs_button != null) {
		qs_button.setAttribute('clearButtonShown', true);
	}
}


function rmOnSearchKeyUp(event) {
/*	-------------------------	read Char in with delay to catch last one
*/
	if ( event.keyCode == 13) { // if 'return' pressed, filter the view immediately
		var desc = document.getElementById("rmSearchText");
		if ( isReminderTabSelected() ) {
			lastRmSearchText =  desc.value;				
			rmHighlightHeader(currentRmSearchItemValue);			
		}
		else {
			lastTodoSearchText =  desc.value;			
			rmHighlightHeader(currentTodoSearchItemValue);	
			
			var tabList = document.getElementById("tabList");	
			var tab =	tabList.selectedItem;
			lastTodoTab = tab.getAttribute( "label");
		}
		searchBarWaitTime = null;
		refillLists();  
		desc.focus();	  
	}
	else {
		searchBarWaitTime = new Date().getTime() + SEARCHBAR_WAIT_DELAY;
		setTimeout(rmOnSearchInput, SEARCHBAR_WAIT_DELAY);	
	}
}

function isListFiltered() {
	if ( isReminderTabSelected() ) {
		if (lastRmSearchText != "") { 
			return true;
		}
	}
	else {
		if (lastTodoSearchText != "") { 
			return true;
		}
	}
	return false;
}

function rmOnSearchFocus(event) {
	if ( !isListFiltered()) {
		var desc = document.getElementById("rmSearchText");
		desc.value = "";		/*  erase the descriptive text */	
	}
}

function rmOnSearchInput() {
/*	-----------------	update Reminder and ToDo lists  & get focus back
*/
	if ( searchBarWaitTime != null ) {
		var currentTime = new Date().getTime();
		// only update the search view if enough time has passed since the last keystroke
		if ( (currentTime + 15)  > searchBarWaitTime ) {	
			
			var desc = document.getElementById("rmSearchText");
			if ( isReminderTabSelected() ) {
				lastRmSearchText =  desc.value;		
				
				if ( lastRmSearchText == "" ) {
					document.getElementById('quick-search-clearbutton').setAttribute('clearButtonShown', false);
				}				
				rmHighlightHeader(currentRmSearchItemValue);			
			
			}
			else {
				lastTodoSearchText =  desc.value;			
				if ( lastTodoSearchText == "" ) {
					document.getElementById('quick-search-clearbutton').setAttribute('clearButtonShown', false);
				}			
				var tabList = document.getElementById("tabList");	
				var tab =	tabList.selectedItem;
				lastTodoTab = tab.getAttribute( "label")
				rmHighlightHeader(currentTodoSearchItemValue);			
			}
			
			refillLists();  
			var desc = document.getElementById("rmSearchText");
	    	desc.focus();	  
		}
	}
}

	
function rmOnBlueClearButton () {
/*	-------------------------------------------- the Clear Button was hit 
*/
	if ( isReminderTabSelected() ) {
		lastRmSearchText = ""; 
		rmCheckMenuItem(currentRmSearchItemValue); 
	} else {
		lastTodoSearchText = "";
		rmCheckMenuItem(currentTodoSearchItemValue);
	}

	rmClearSearch(true);
}

function rmChangeQuickSearchMode(aMenuItem)  {
/*	-----------------------------------------------------
	for current TAB remember 'menuItem' and clear input 
*/
	var searchText = document.getElementById('rmSearchText')		
	searchText.value = "";
	
	if ( isReminderTabSelected() ) {
		lastRmSearchText = ""; 		
	} else {
		lastTodoSearchText = "";
	}	
	
	rmCheckMenuItem(aMenuItem.value); 
	rmClearSearch(true);
	
	// move focus out of the text field (so user has to refocus)
	if ( isReminderTabSelected() ) {
		selectNewReminderText();
	}
	else {
		var desc = document.getElementById("addTodoButton");
    	desc.focus();	 
	}
}

/**
 * 	reset menuItem and clear input
 */	
function rmInitQuickSearchPopup() {
// -----------------------------------------------------
	if ( isReminderTabSelected() ) {
		rmCheckMenuItem(currentRmSearchItemValue);  
	}
	else {
		rmCheckMenuItem(currentTodoSearchItemValue);  
	}
	
	var rmSearchText = document.getElementById('rmSearchText')	
	rmSearchText.style.color="grey";
	
	if ( isListFiltered() ) {
		rmClearSearch();
	}
	
}	


function rmClearSearch(forceRefresh) {
	/*  clear input text and the blue button and set to 'grey' text */
	if ( document.getElementById('quick-search-clearbutton') != null ) {
		document.getElementById('quick-search-clearbutton').setAttribute('clearButtonShown', false);
	}
	
	var rmSearchText = document.getElementById('rmSearchText')	
	rmSearchText.style.color="grey";
	
	if ( forceRefresh || isListFiltered() ) {
		/* update Reminder and ToDo lists  & get focus back */
		refillLists(); 
	}
}


function rmShowQSearch(isTabChange) {	
/* ------- call with tab-change to change child and preselected values 
*/
	var rmSearchText = document.getElementById('rmSearchText');
	if ( isReminderTabSelected() ) { /* --- Reminders selected --- */	
		if ( isTabChange ) {
			var clonedQTPicker = rmSearchText.cloneNode( true );
			rmSearchText.parentNode.removeChild( rmSearchText );
			document.getElementById("rmSearchTextBox").appendChild( clonedQTPicker );
		}
	
		/* ---- if previous ReminderSearch, rebuild  ---- */
		if ( isListFiltered() ) { 
			rmCheckMenuItem(currentRmSearchItemValue); 		
			document.getElementById('rmSearchText').value = lastRmSearchText ;
			
			clonedQTPicker.clearButtonShown = true;						
			clonedQTPicker.style.color="blue";
			
			if ( isTabChange ) { // only update list on tab change (not on initial load)
				/* update Reminder and ToDo lists  & get focus back */				
				refillLists(); 
				document.getElementById('rmSearchText').focus();	  			
			}
		}		
		else {  /*	no previous remembered values	*/
				/*	init input field & parameters  */
			rmInitQuickSearchPopup();
		}		
	}
	else {  /* ---	Todos oder user-Lists selected 	--- */
		/*   load XUL new */
		if ( isTabChange ) {
			var clonedQTPicker = rmSearchText.cloneNode( true );
			rmSearchText.parentNode.removeChild( rmSearchText );
			document.getElementById("todoSearchTextBox").appendChild( clonedQTPicker );
		}
		
		if ( isListFiltered() ) { 					
			var tabList = document.getElementById("tabList");	
			var tab =	tabList.selectedItem;
			var currentTabName = tab.getAttribute( "label");
			if ( lastTodoTab != "" && currentTabName != lastTodoTab ) { // tab has changed; clear everything
				rmOnBlueClearButton();  // clear this todo search info
			}
			else {
				rmCheckMenuItem(currentTodoSearchItemValue); 			
				document.getElementById('rmSearchText').value = lastTodoSearchText ;
			
				clonedQTPicker.clearButtonShown = true;						
				clonedQTPicker.style.color="blue";			
			}
		}
		else {			
			rmInitQuickSearchPopup();
		}
	}
}



function selectTab() {	
		
	// give focus to the reminder/todo description when switching tabs
	selectCalendarSync = false;
	var tabList = document.getElementById("tabList");	 
	var tabIndex =	tabList.selectedIndex;

	var panels = document.getElementById("tabPanelID");	
		
	rmFx_View.SetTitel(isReminderTabSelected());        //gW_View&Filter
		
	var currentReminderPanel = document.getElementById("treeparent").parentNode;
	var currentTodoPanel = document.getElementById("todoTreeparent").parentNode;
	if ( !isReminderTabSelected() ) {
		if ( panels.childNodes[tabIndex] == currentTodoPanel ) { // we clicked on the same tab...
			if ( reminderFoxTabDirtied ) {
				reminderFoxTabDirtied = false;
				removeAllListItems( false, true );
				
				fillList( false, true );
			}
		}
		else {
			// this is the active tab -  we want to move its contents to new tab				
			// first remove all the tree children from old tab (clear its todo list; it will be repopulated with
			// todos from new list)
			var treeChildren = document.getElementById("todoTreechildren");
			if ( treeChildren != null && treeChildren.childNodes.length > 0 ) {
				     while (treeChildren.hasChildNodes()) {
		    	 		treeChildren.removeChild(treeChildren.firstChild);
		    	 	}		
			}					
	
			// now move all elements from old tab to new tab
			var newPanel = panels.childNodes[tabIndex];
			while (currentTodoPanel.hasChildNodes()) {
					var child =  currentTodoPanel.removeChild(currentTodoPanel.firstChild);
					newPanel.appendChild(child);				    			
	  	 	}	
			// add new todos to the new tab's list
			fillList( false, true );
		}
		
		var desc = document.getElementById("addTodoButton");
    	desc.focus();	
	}
	else {
		if ( isSubscribedCalendarTabSelected() ) {
			var subscribedCalArr =	getSubscribedCalendars();
			var tabList = document.getElementById("tabList");	
			var tab =	tabList.selectedItem;
			var tabIndex =	tabList.selectedIndex;
			var index = tab.id.indexOf( ':' );		
			var name = tab.id.substring( index +1 , tab.id.length );
			var subscribedCal = subscribedCalArr[name];
			if ( subscribedCal != null  && subscribedCal.length == 0 ) {
				subscribedCal = null;
				subscribedCalArr[name] = subscribedCal;
			}
			
			
			
			document.getElementById("addReminderButton").setAttribute( "disabled", true );
		}
		else {
				document.getElementById("addReminderButton").removeAttribute( "disabled" );
		}
		if ( panels.childNodes[tabIndex] == currentReminderPanel ) { // we clicked on the same tab...
//				if ( reminderFoxTabDirtied ) {
//					reminderFoxTabDirtied = false;
//					removeAllListItems( false, true );
//					fillList( false, true );
//				}
		}
		else {
			// clear status text 
			rmFxCore.statusSet ("");
			
			calendarReminderArray = null;  // clear array (in case sorted)
			
			// this is the active tab -  we want to move its contents to new tab				
			// first remove all the tree children from old tab (clear its todo list; it will be repopulated with
			// todos from new list)
			var treeChildren = document.getElementById("treechildren");
			if ( treeChildren != null && treeChildren.childNodes.length > 0 ) {
			     while (treeChildren.hasChildNodes()) {
	    	 		treeChildren.removeChild(treeChildren.firstChild);
	    	 	}		
			}					
	
			// now move all elements from old tab to new tab
			var newPanel = panels.childNodes[tabIndex];
			while (currentReminderPanel.hasChildNodes()) {
					var child =  currentReminderPanel.removeChild(currentReminderPanel.firstChild);
					newPanel.appendChild(child);				    			
	  	 	}	
	  	 		  	 	
			// add new todos to the new tab's list
			fillList( true, false );							
		}
		selectNewReminderText();					
	}

	selectCalendarSync = true;   
	// show calendar based on button state			
	reminderFox_showCal();		
	
	oeDatePicker.redrawDays();
	
	//  dynamically insert Quick-Search box 
	rmShowQSearch(true);   //true= need to update 'fillList'	//gW_Search 
}

function isReminderTabSelected() {
	var remindersTab = document.getElementById("remindersTab");
	if ( remindersTab == null || remindersTab.selected ) {
		return true;
	}
	else {
		if ( isSubscribedCalendarTabSelected()) {
			return true;
		}
		else {
			return false;
		}
	}	
}

function isSubscribedCalendarTabSelected() {
	var tabList = document.getElementById("tabList");	
	var tab =	tabList.selectedItem;
	var listName = tab.getAttribute( "label");
	
	var subscriptions = reminderFox_getSubscriptions();	
	var url = subscriptions[listName];
	if ( url != null && url.length > 0 ) {
		return true;
	}
	else {
		return false;
	}	
}

function reminderFox_removeListItems(listID) {
		var todoTreeChildren = document.getElementById(listID);
	    while (todoTreeChildren.hasChildNodes()) {
	    	todoTreeChildren.removeChild(todoTreeChildren.firstChild);
	  	}		
}

function reminderFox_enableAddTodoButton(event) {
		var newbutton= document.getElementById("newTodoButton");
		newbutton.removeAttribute( "disabled");
}


function rmFx_checkLoaded() {
	if (getAllSelectedReminders().length == 0) {
		document.getElementById("treechildren-contextmenu-sendReminder").setAttribute("disabled", "true");
	}	
	if (getAllSelectedTodos().length == 0) {
		document.getElementById("treechildren-contextmenu-sendTodos").setAttribute("disabled", "true");
	}	
}

function toggleFoxy(){
	var hideFoxy = reminderFox_getPreferenceValue( REMINDER_FOX_HIDE_FOX_PAW );
	
	hideFoxy = !hideFoxy;  // toggle the pref
	reminderFox_setPreferenceValue( REMINDER_FOX_HIDE_FOX_PAW, hideFoxy );
	
	if (hideFoxy) {
		document.getElementById('foxy-calendar').setAttribute("hidden", "true");
	}
	else {
		document.getElementById('foxy-calendar').removeAttribute("hidden");
	}
}

function activateCalendarFoxyContext(event){
	var hideFoxy = reminderFox_getPreferenceValue( REMINDER_FOX_HIDE_FOX_PAW );
	if (hideFoxy) {
		document.getElementById('hide-foxy-menu').setAttribute("hidden", "true");
		document.getElementById('show-foxy-menu').removeAttribute("hidden");
	}
	else {
		document.getElementById('show-foxy-menu').setAttribute("hidden", "true");
		document.getElementById('hide-foxy-menu').removeAttribute("hidden");
	}
}


function loadReminders() {

	  // show links on calendar
	 var optionsLinksBox = document.getElementById("option-links");
	 if ( optionsLinksBox != null ) { 
		 optionsLinksBox.removeAttribute("hidden");
	}
	
	
	// set Filter display based on preference
	showFilters = reminderFox_prefs.getBoolPref(
		REMINDER_FOX_PREF + "." + REMINDER_FOX_SHOW_FILTERS);
	updateFilters();
	
	// set Filter display based on preference
	showSidebar = reminderFox_prefs.getBoolPref(
		REMINDER_FOX_PREF + "." + REMINDER_FOX_SHOW_SIDEBAR);
		
	var hideGayPaw = reminderFox_getPreferenceValue( REMINDER_FOX_HIDE_FOX_PAW );
	if ( hideGayPaw ) {
		document.getElementById('foxy-calendar').setAttribute("hidden", "true");	
	}
		
	  showCalendar();

	//gW_Contact Handling	   	
 	rmFxMsg.whichMessenger();	  	
	var addContext = document.getElementById("treechildren-contextmenu");
	if (addContext != null)
		 addContext.addEventListener("popupshowing", rmFxPopupCheckMenus, false);

	var addContext = document.getElementById("todo-treechildren-contextmenu");
	if (addContext != null)
		 addContext.addEventListener("popupshowing", rmFxPopupCheckMenus, false); 

	// set default filters
	var defaultFilterReminderIndex = reminderFox_getPreferenceValue( REMINDER_FOX_DEFAULT_FILTER_REMINDER, 0 );
	var filterList = document.getElementById("displayType");
	filterList.selectedIndex = defaultFilterReminderIndex;	
	
	var defaultFilterTodoIndex = reminderFox_getPreferenceValue( REMINDER_FOX_DEFAULT_FILTER_TODO, 0 );
	filterList = document.getElementById("displayTypeTodo");
	filterList.selectedIndex = defaultFilterTodoIndex;	
	rmFx_View.prefViewCurrentLoad();  //gW_View Current    get the 'CurrentView' from prefs and set gViewLabel/Items
	rmFx_View.SetTitel("reminders");
	
	try {
		dateVariableString = reminderFox_getUnicodePref(REMINDER_FOX_PREF + "." + REMINDER_FOX_LIST_DATE_LABEL);
		if ( dateVariableString != REMINDER_FOX_LIST_DATE_LABEL_DEFAULT) {
			useDefaultDate = false;
		}
	} catch(e) {
		 dateVariableString = REMINDER_FOX_LIST_DATE_LABEL_DEFAULT;
	}	
	
	
	reminderFox_highlightTodayPreference = REMINDER_FOX_HIGHLIGHT_TODAYS_REMINDERS_DEFAULT;			
	try {
		reminderFox_highlightTodayPreference = reminderFox_prefs.getBoolPref(REMINDER_FOX_PREF + "." + REMINDER_FOX_HIGHLIGHT_TODAYS_REMINDERS);
	} catch(e) {
	}			

	try {
		REPEAT_PREVIOUS_OCCURRENCES = reminderFox_prefs.getIntPref(REMINDER_FOX_PREF + "." + REMINDER_FOX_REPEAT_PREVIOUS_OCCURRENCES);
	} catch(e) {
		 REPEAT_PREVIOUS_OCCURRENCES = -1;
	}	

	try {
		REPEAT_UPCOMING_OCCURRENCES =  reminderFox_prefs.getIntPref(REMINDER_FOX_PREF + "." + REMINDER_FOX_REPEAT_UPCOMING_OCCURRENCES);
	} catch(e) {
		 REPEAT_UPCOMING_OCCURRENCES = -1;
	}		
	
	try {
		HIDE_COMPLETED_ITEMS =  reminderFox_prefs.getBoolPref(REMINDER_FOX_PREF + "." + REMINDER_FOX_HIDE_COMPLETED_ITEMS);
	} catch(e) {
		 HIDE_COMPLETED_ITEMS = false;
	}			
	var hideCompletedContextMenu = document.getElementById("treechildren-contextmenu-hideCompleted");
	var hideCompletedTodosContextMenu = document.getElementById("treechildren-contextmenu-hideCompleted2");
	if ( HIDE_COMPLETED_ITEMS ) {
		hideCompletedContextMenu.setAttribute("checked", "true");		
		hideCompletedTodosContextMenu.setAttribute("checked", "true");		
	}
	else {
		hideCompletedContextMenu.setAttribute("checked", "false");		
		hideCompletedTodosContextMenu.setAttribute("checked", "false");		
	}

	// create todo lists
 	var todoLists = reminderFox_getUnicodePref(REMINDER_FOX_PREF + "." + REMINDER_FOX_TODO_LISTS);
 	if ( todoLists == null ) {
 		todoLists = "";
 	}
 	
 	// check to see if we need to update the todoLists....
 	var update = false;
 	var todosArr =	reminderFox_getReminderTodos();
 	var todoListsArray = todoLists.split(",");
 	for ( var n in todosArr ) {
 		if ( n !=REMINDER_FOX_DEFAULT_TODOS_CATEGORY ) {
	 		var found = false;
			for ( var i = 0; i < todoListsArray.length; i++ ) {
				if ( n == todoListsArray[i]) {
					found = true;
					break;
				}
			}
			if ( !found ) {
				if ( todoLists.length > 0 ) {
					todoLists = todoLists + "," + n;
				}
				else {
					todoLists = n;
				}
				update = true;
			}
 		}
	}
	if ( update ) {
		reminderFox_setUnicodePref( REMINDER_FOX_TODO_LISTS, todoLists);		
	}
	
	
 	
	if ( todoLists != null  && todoLists.length > 0 ) {
		var todoListsArray = todoLists.split(",");
		var tabList = document.getElementById("tabList");		
		var panels = document.getElementById("tabPanelID");	
		var todosTab = document.getElementById("todosPanel");
		var remindersTab = document.getElementById("reminderPanel");
		
		for ( var i = 0; i < todoListsArray.length; i++ ) { 
			var tabListItem = reminderFox_trim( todoListsArray[i] );	
			var newTabList = document.createElement("tab");
			newTabList.setAttribute( "id",   "reminderFoxList:" + tabListItem );
			newTabList.setAttribute( "label", tabListItem );
			tabList.appendChild(newTabList);
			
			var newtabpanel = todosTab.cloneNode( false );							
			newtabpanel.setAttribute( "id","reinderFoxListPanel:" + tabListItem  );
	    	panels.appendChild(newtabpanel);
		}
	}
	
	// get sort columns
	listSortMap = new Array();
	var sortColumnsStr = reminderFox_getUnicodePref(REMINDER_FOX_PREF + "." + REMINDER_FOX_SORT_COLUMNS_PREF);
 	if ( sortColumnsStr != null && sortColumnsStr != ""  ) {
 		var sortColumnsStrArray = sortColumnsStr.split(",");
 		for ( var i = 0; i < sortColumnsStrArray.length; i++ ) { 
			var listName =  sortColumnsStrArray[i];
			i++;
			var sortCol = sortColumnsStrArray[i];
			i++;
			var sortDir = parseInt( sortColumnsStrArray[i] );
			listSortMap[listName] = { sortColumn: sortCol, sortDirection:  sortDir };
 		}
 	}
 		
	var syncedUp = reminderFox_ensureRemindersSynchronized();

	if ( isTodoTabSorted()) {
		reminderFoxTabDirtied = true;  // we need to refill the todo tab the first time you select it to resort it
	}

	fillList(true, true); 

	// select appropriate tab
	if ( window.arguments != null ) {
		var currentTab = window.arguments[0];
		if ( currentTab == "todos" ) {
			var todosTab = document.getElementById("todosTab");
			var tabbox = document.getElementById("tabbox");
			tabbox.selectedTab = todosTab;		
		}
	}
	
   	//showCalendar();
	
	var todaysDate = new Date();
	oeDatePicker.onpopupshowing(todaysDate);
	selectCalendarSync = true;	

	// dynamically insert Quick-Search box 
	rmShowQSearch();  //false=no update "fillLists"  //gW_Search 
	
	// jump to showing today's date when the calendar shows
	oeDatePicker.gotoToday();

	// start synchronizing in background (if that network option is set)
	setTimeout( reminderFox_ensureRemoteRemindersSynchronizedInEditWindow, 1 );
	
	if ( window.arguments != null  && window.arguments[1] != null ) { 
		var editReminderID = window.arguments[1]. editID;
		if ( editReminderID != null ) {
			if (  window.arguments[1].isAReminder == "true" ) {
				selectReminderById(editReminderID	);
				window.setTimeout( editReminder, 1 );	
			}
			else {
				selectTodoById( window.arguments[1].todoList, editReminderID	);
				window.setTimeout( editTodo, 1 );	
			}
		}
	}	
}


function reminderFox_ensureRemoteRemindersSynchronizedInEditWindow() {
	// sync 'em up 
	var networkSync = REMINDER_FOX_NETWORK_SYNCHRONIZE_DEFAULT;		
	try {
		networkSync = reminderFox_prefs.getBoolPref(REMINDER_FOX_PREF + "." + REMINDER_FOX_NETWORK_SYNCHRONIZE);
	} catch(e) {
	}	
	if ( networkSync ) {
		rmFxCore.statusSet (g_reminderFoxBundle.getString("rf.add.network.status.label"));
		reminderFox_download_Startup_headless(REMINDER_FOX_UI_MODE_HEADLESS_SHOW_ERRORS,reminderFox_synchronizeEditWindowCallback );
	}	
}

function reminderFox_synchronizeEditWindowCallback( statustxtString, actionID) {
		// var statusTxt = document.getElementById("reminderFox-network-status");
		
		if ( actionID == 1 ) {  // completed successfully (remote and local are equal, or were uploaded)
			rmFxCore.statusSet ("");
			   
		}
		else if ( actionID == 2 ) { // reminders were downloaded,  need to refresh reminders 
			modifiedReminders();

			reminderFox_clearRemindersAndTodos();		
			
			selectCalendarSync = false;
		 	// remove all of the calendar items and re-add them
			removeAllListItems( true, true);	  
			calendarReminderArray = null;  // null out in case reminder columns are sorted
			calendarTodoArray = null;
			fillList(true, true);	
			selectCalendarSync = true;   
		   
		   oeDatePicker.redrawYear();
		   oeDatePicker.redrawDays();			
		//  statusTxt.setAttribute("value", "");   
			rmFxCore.statusSet ("");
		   
			// check to see if a reminder is being edited (such as if you opened the edit window from an alarm).
			// If so, then we need to replace the old reminder instance (which is no longer in memory) with a newly
			// retrieved one from the new model in memory
		   var windowManager = Components.classes['@mozilla.org/appshell/window-mediator;1'].getService();
		   var windowManagerInterface = windowManager.QueryInterface(Components.interfaces.nsIWindowMediator);
		   var topWindow = windowManagerInterface.getMostRecentWindow("window:reminderFoxReminderOptionsDialog");
		   if (topWindow) {		 
				var staleReminder =topWindow. arguments[0].reminder;
				if ( staleReminder != null ) {
					var refreshedReminder = reminderFox_getRemindersById( staleReminder.id, getCurrentReminderList()  );
					if  ( refreshedReminder != null ) {
						topWindow. arguments[0].reminder = refreshedReminder;
					}
				}
		   }  		   
		}
		else {
//			statusTxt.setAttribute("value", statustxtString);
			rmFxCore.statusSet (statustxtString);
		}
		
}

function repopulateListForYear(oldYear, newYear) {
	selectCalendarSync = false;
 	// remove all of the calendar items and re-add them
	removeAllListItems( true, false);	 
	calendarReminderArray = null;  // null out in case reminder columns are sorted
	calendarTodoArray = null;
	fillList(true, false);	
	selectCalendarSync = true;
}

function fillList(  fillReminders,  fillTodoList, ignoreHighlight) {
	//rmFxUtil.dump2Console ('dateSpan', "fillList     isTabSorted() :" + isTabSorted());

	var i;
	if ( fillReminders ) {
		if ( isTabSorted() ) {	
			ignoreHighlight = true;
			var tabList = document.getElementById("tabList");	
			var tab =	tabList.selectedItem;
			var tabName = tab.getAttribute( "label");
		 	var direction = listSortMap[tabName].sortDirection;
		 	if ( direction == REMINDER_FOX_SORT_DIRECTION_ASCENDING ) {
			 	var columnName  = listSortMap[tabName].sortColumn;
				if ( columnName == "dateColLabel"  ) {
					ignoreHighlight = false;
				}
		 	}
			
			fillListSortReminders(true); 
			
			if ( !ignoreHighlight ) {
				// Note: need to launch this as a separate thread as in FF3.0 when dealing with remote 
				// calendars downloading, this call calls tree.select() which fails for some reason (must
				// be some thread/timing issue.  Calling this separate thread seems to fix it
				setTimeout( highlightClosestUpcomingReminder, 0, new Date());		
				//highlightClosestUpcomingReminder( new Date());		
			}
			
		}
		else { 
			clearAllSortColumns();  // or could put this in the select tab logic...  may be better
			createCalendarReminderArray();
			var todaysDate = new Date();
			var monthArray, dayReminderArray;
			var monthIndex, dayIndex, reminderIndex;
			for ( monthIndex = 0; monthIndex < 12; monthIndex++ ) {
				monthArray = calendarReminderArray[monthIndex];
				if ( monthArray != null ) {
					for ( dayIndex = 0; dayIndex < 31; dayIndex++ ) {
						dayReminderArray = monthArray[dayIndex];
						if ( dayReminderArray != null ) {
							for ( reminderIndex = 0; reminderIndex < dayReminderArray.length; reminderIndex++ ) {
								createListItemSorted(dayReminderArray[reminderIndex], todaysDate);
							}
						}
					}
				}
			}
			// now that we've added the sorted reminders in the list, let's
			// select (highlight) today's reminder or the next upcoming reminder
			if ( !ignoreHighlight ) {
				// Note: need to launch this as a separate thread as in FF3.0 when dealing with remote 
				// calendars downloading, this call calls tree.select() which fails for some reason (must
				// be some thread/timing issue.  Calling this separate thread seems to fix it
				setTimeout( highlightClosestUpcomingReminder, 0, new Date());		
				//highlightClosestUpcomingReminder( new Date());		
			}
			
			// bit of a hack here - for some reason at some times these filtered elements were indeed added to the 
			// treechildren, but wouldn't show in the UI.  calling the treeselection.select() seemed to fix that, but 
			// not sure why - possibly that the current view was scrolled off the screen
			if ( isListFiltered() ) {
				var treeChildren = document.getElementById("treechildren");
				var treeSelection = document.getElementById("reminderTree").view.selection;	
				var treeitems = treeChildren.childNodes;
				if ( treeitems.length > 0 ) {
					//treeSelection.select(0);
					//highlightClosestUpcomingReminder( new Date());		
					setTimeout( treeSelect, 0);	
					setTimeout( highlightClosestUpcomingReminder, 0, new Date());	
				}
			}
		}
	}
	
	if ( fillTodoList ) {
		//calendarTodoArray = null;
		createCalendarTodoArray()		
		
		if ( isTabSorted() ) {
			fillListSortTodos();
		}
		else {
			clearAllSortColumns();    //  or could put this in the select tab logic...  may be better
			
			var displayList = document.getElementById("displayTypeTodo");
			// if one of the filters is set, only show those dates in the calendar array	
			// only if the index is < 8; that means one of the "date-based" filters is set. 
			// If the index is higher, that means a Custom View, and we should go through the non-date based filtering
			if ( displayList != null && displayList.selectedIndex > 0 && displayList.selectedIndex < 8  ) {
				var todaysDate = new Date();
				var monthArray, dayReminderArray;
				var monthIndex, dayIndex, reminderIndex;
				for ( monthIndex = 0; monthIndex < 12; monthIndex++ ) {
					monthArray = calendarTodoArray[monthIndex];
					if ( monthArray != null ) {
						for ( dayIndex = 0; dayIndex < 31; dayIndex++ ) {
							dayReminderArray = monthArray[dayIndex];
							if ( dayReminderArray != null ) {
								for ( reminderIndex = 0; reminderIndex < dayReminderArray.length; reminderIndex++ ) {
									createTodoListItem(dayReminderArray[reminderIndex], false, todaysDate, false);
								}
							}
						}
					}
				}				 
			}
			
			else {
				
				// put that other check in the createTodoArray  
				var todaysDate = new Date();
          		var reminderTodos = getCurrentTodoList();
				for( i = 0; i < reminderTodos.length; i++) {			 
					createTodoListItem(reminderTodos[i], false, todaysDate, false);
				}
				highlightTodo();
			}
		}
	}
   	selectNewReminderText();
}

function treeSelect() {
	var treeSelection = document.getElementById("reminderTree").view.selection;	
	var treeChildren = document.getElementById("treechildren");
	var treeitems = treeChildren.childNodes;
	if ( treeitems.length > 0 ) {
		treeSelection.select(0);
	}
}

function doFindNext() {
	if ( lastSearchString == null ) {
		doFind();
	}
	else {
		if ( !isReminderTabSelected() ) {
			 findTodo();
		}
		else {
			 findReminder();
		}
	}
}

function doShowAll() {
	SHOW_ALL_REMINDERS = true;
	HIDE_ALL_REMINDERS = false;
	
   // redraw the year and the days
   repopulateListForYear( null , oeDatePicker.gSelectedDate.getFullYear() );
   
   oeDatePicker.redrawYear();
   oeDatePicker.redrawDays();
}

function doHideAll() {
	SHOW_ALL_REMINDERS = false;
	HIDE_ALL_REMINDERS = true;
	
   // redraw the year and the days
   repopulateListForYear( null , oeDatePicker.gSelectedDate.getFullYear() );
   
   oeDatePicker.redrawYear();
   oeDatePicker.redrawDays();
}

function toggleHideCompletedItems() {
	HIDE_COMPLETED_ITEMS = !HIDE_COMPLETED_ITEMS;
	
	var hideCompletedContextMenu = document.getElementById("treechildren-contextmenu-hideCompleted");
	var hideCompletedTodosContextMenu = document.getElementById("treechildren-contextmenu-hideCompleted2");
	if ( HIDE_COMPLETED_ITEMS ) {
		hideCompletedContextMenu.setAttribute("checked", "true");		
		hideCompletedTodosContextMenu.setAttribute("checked", "true");		
	}
	else {
		hideCompletedContextMenu.setAttribute("checked", "false");		
		hideCompletedTodosContextMenu.setAttribute("checked", "false");		
	}	
	
   // redraw the year and the days
   //repopulateListForYear( null , oeDatePicker.gSelectedDate.getFullYear() );
	selectCalendarSync = false;
 	// remove all of the calendar items and re-add them
	removeAllListItems( true, true);
	rmFx_View.SetTitel();
	fillList(true, true);	//   refillLists();  -tfm 11/24/2010 - don't use refillLists as that only fills selected list; we want both todo's and reminders filled
	
	selectCalendarSync = true;   
   
   oeDatePicker.redrawYear();
   oeDatePicker.redrawDays();
}


function doFind() {
	var nsIPromptService = Components.interfaces.nsIPromptService;
	var nsPrompt_CONTRACTID = "@mozilla.org/embedcomp/prompt-service;1";
	var gPromptService = Components.classes[nsPrompt_CONTRACTID].getService(nsIPromptService);
	var result = { value: lastSearchString };
	var dummy = { value: 0 };
	var title;
	if ( !isReminderTabSelected() ) {
		 title =  g_reminderFoxBundle.getString("rf.add.find.todo.title");
	}
	else {
		 title =  g_reminderFoxBundle.getString("rf.add.find.title");
	}
	
	if (gPromptService.prompt(window,
                            title,
                            g_reminderFoxBundle.getString("rf.add.find.description"),
                            result,
                            null,
                            dummy)) {
                            
            lastSearchString = result.value;
          
			// only bring up find dialog if reminders tab is selected
			if ( isReminderTabSelected() ) {
				findReminder();          
			}
			else {
				findTodo();
			}          
        	
    }    
}

function findReminder( ) {
	var i;
	var item;
	var row;
	var descCell;
	var descCellLabel;
	
	var selectedTreeItemIndex = document.getElementById("reminderTree").currentIndex;
	// if nothing selected, default to start of list
	if ( selectedTreeItemIndex == -1 ) {
		selectedTreeItemIndex = 0;
	}
		
	var treeChildren = document.getElementById("treechildren");
	var selectedTreeItem = treeChildren.childNodes[selectedTreeItemIndex];

	var dateLabel = selectedTreeItem.childNodes[0].childNodes[0].getAttribute("label");
	var descLabel = selectedTreeItem.childNodes[0].childNodes[1].getAttribute("label");
  	var caseInsensitiveLastSearchString = lastSearchString.toUpperCase();

	var treeitems = treeChildren.childNodes;
	var startIndex = selectedTreeItemIndex;
	if ( startIndex + 1 < treeitems.length ) {
		startIndex = startIndex + 1;
	}
	else { 
		startIndex = 0;
	}

	var foundIndex = -1;
	for ( i=startIndex; i < treeitems.length; i++) {
		item = treeitems[i];
		row = item.childNodes[0];
		descCell = row.childNodes[1];
		descCellLabel = descCell.getAttribute("label");
		descCellLabel = descCellLabel.toUpperCase();

		if ( descCellLabel.indexOf( caseInsensitiveLastSearchString ) != -1  ) {
			foundIndex = i;

			break;
		}
	}
	
	if ( foundIndex == -1 ) {
		for ( i=0; i < startIndex; i++) {
			item = treeitems[i];
			 row = item.childNodes[0];
			descCell = row.childNodes[1];
			descCellLabel = descCell.getAttribute("label");
			descCellLabel = descCellLabel.toUpperCase();

			if ( descCellLabel.indexOf( caseInsensitiveLastSearchString ) != -1  ) {
				foundIndex = i;
				break;
			}
		}
	}
	
	// if we found a search match, then highlight the new reminder in the list
	if ( foundIndex != -1 ) {		
		var treeSelection = document.getElementById("reminderTree").view.selection		
		treeSelection.select(foundIndex);
		
		// make sure that newly selected row is shown in scroll pane
		var value = document.getElementById("treeparent").value;
	  	var tree = document.getElementById("reminderTree");			
		var boxobject = tree.boxObject;
		boxobject.QueryInterface(Components.interfaces.nsITreeBoxObject);
		
		// make sure it shows up at the top if possible
		var first = boxobject.getFirstVisibleRow();
		var last = boxobject.getLastVisibleRow();
		if ( foundIndex < first || foundIndex > last ) {				
			boxobject.scrollToRow(treeitems.length - 9);
		}
		
		var previousReminderOffset = 3;
		if ( foundIndex < previousReminderOffset ) { 
			boxobject.ensureRowIsVisible(i);
		}
		else {
			boxobject.ensureRowIsVisible(foundIndex  - previousReminderOffset);
		}
	}
}


function findTodo( ) {
	var i;
	var item;
	var row;
	var descCell;
	var descCellLabel;
	
	var selectedTreeItemIndex = document.getElementById("todoTree").currentIndex;
	// if nothing selected, default to start of list
	if ( selectedTreeItemIndex == -1 ) {
		selectedTreeItemIndex = 0;
	}
		
	var treeChildren = document.getElementById("todoTreechildren");
	var selectedTreeItem = treeChildren.childNodes[selectedTreeItemIndex];

	var descLabel = selectedTreeItem.childNodes[0].childNodes[1].getAttribute("label"); // 1 is description for Todos
    var caseInsensitiveLastSearchString = lastSearchString.toUpperCase();

	var treeitems = treeChildren.childNodes;
	var startIndex = selectedTreeItemIndex;
	if ( startIndex + 1 < treeitems.length ) {
		startIndex = startIndex + 1;
	}
	else { 
		startIndex = 0;
	}

	var foundIndex = -1;
	for ( i=startIndex; i < treeitems.length; i++) {
		item = treeitems[i];
		row = item.childNodes[0];
		descCell = row.childNodes[1]; // 1 is description for todo's
		descCellLabel = descCell.getAttribute("label");
		descCellLabel = descCellLabel.toUpperCase();
		if ( descCellLabel.indexOf( caseInsensitiveLastSearchString ) != -1  ) {
			foundIndex = i;

			break;
		}
	}
	
	if ( foundIndex == -1 ) {
		for ( i=0; i < startIndex; i++) {
			item = treeitems[i];
			 row = item.childNodes[0];
			descCell = row.childNodes[1]; // 1 is description for ToDo's
			descCellLabel = descCell.getAttribute("label");
			descCellLabel = descCellLabel.toUpperCase();

			if ( descCellLabel.indexOf( caseInsensitiveLastSearchString ) != -1  ) {
				foundIndex = i;
				break;
			}
		}
	}
	
	// if we found a search match, then highlight the new reminder in the list
	if ( foundIndex != -1 ) {		
		var treeSelection = document.getElementById("todoTree").view.selection		
		treeSelection.select(foundIndex);
		
		// make sure that newly selected row is shown in scroll pane
		var value = document.getElementById("treeparent").value;
	  	var tree = document.getElementById("todoTree");			
		var boxobject = tree.boxObject;
		boxobject.QueryInterface(Components.interfaces.nsITreeBoxObject);
		
		// make sure it shows up at the top if possible
		var first = boxobject.getFirstVisibleRow();
		var last = boxobject.getLastVisibleRow();
		if ( foundIndex < first || foundIndex > last ) {				
			boxobject.scrollToRow(treeitems.length - 9);
		}
		
		var previousReminderOffset = 3;
		if ( foundIndex < previousReminderOffset ) { 
			boxobject.ensureRowIsVisible(i);
		}
		else {
			boxobject.ensureRowIsVisible(foundIndex  - previousReminderOffset);
		}
	}
}

function selectNewReminderText() {
   var desc = document.getElementById("addReminderButton");  
    desc.focus();
}

function toggleFilters(){
	showFilters = !showFilters;
	updateFilters();
}

function updateFilters() { 
	var filtersBox = document.getElementById("filter-box");
	var filtersBoxTodo = document.getElementById("filter-box-todo");
	
	if (showFilters ) {
		filtersBox.removeAttribute("hidden");
		filtersBoxTodo.removeAttribute("hidden");
		document.getElementById("filter-label").setAttribute("value", g_reminderFoxBundle.getString("rf.add.hideFilters") );
	}
	else {
		filtersBox.setAttribute("hidden", "true");
		filtersBoxTodo.setAttribute("hidden", "true");
		document.getElementById("filter-label").setAttribute("value", g_reminderFoxBundle.getString("rf.add.showFilters") );
	}
}


function toggleSidebar(){
	showSidebar = !showSidebar;
	updateSidebar();
}

function updateSidebar() { 
	var calendar = document.getElementById("oe-date-picker-overlay-box");		
	if ( showSidebar ) {
		calendar.removeAttribute("hidden");	
		document.getElementById("showSidebar").setAttribute("hidden", "true");	
		document.getElementById("showSidebar-todo").setAttribute("hidden", "true");				
	}
	else {
		calendar.setAttribute("hidden", "true");	
		document.getElementById("showSidebar").removeAttribute("hidden");
		document.getElementById("showSidebar-todo").removeAttribute("hidden");		
	}
}



function showCalendar() {			
  // if not the default medium size, then we need to resize the calendar
  // In that case, we need to initially hide the calendar widget and then show it in a setTimeout thread
  // because on FF2.x, the sizing gets screwed up
  var calendarSize = 1;
  try {
		calendarSize = reminderFox_prefs.getIntPref(REMINDER_FOX_PREF + "." + REMINDER_FOX_CALENDAR_SIZE);
	} catch(e) {		
	}	
	if ( calendarSize != 1 ) { 
		oeDatePicker.resizeCalendar();
		var newCalendarNode  = document.getElementById("oe-date-picker-overlay-box");	
		newCalendarNode.setAttribute("hidden", "true");	
		setTimeout( reminderFox_showCal, 0);
	}
	else {
		reminderFox_showCal();
	}
}


function reminderFox_showCal() {
	var calendar = document.getElementById("oe-date-picker-overlay-box");		
	if ( isReminderTabSelected() ) {  
		if ( calendar.parentNode != document.getElementById("treeparent") ) {			
			var clonedDatePicker = calendar.cloneNode( true );
			calendar.parentNode.removeChild( calendar );		
			document.getElementById("treeparent").appendChild( clonedDatePicker );
		}
		
	}
	else {
		if ( calendar.parentNode != document.getElementById("todoTreeparent") ) {
			var clonedDatePicker = calendar.cloneNode( true );
			calendar.parentNode.removeChild( calendar );		
			document.getElementById("todoTreeparent").appendChild( clonedDatePicker );
		}
	}
	
	updateSidebar();
}

function reminderSelected(event) {
	if ( selectCalendarSync ) {
		var selectedTreeItemIndex = document.getElementById("reminderTree").currentIndex; 
		if ( selectedTreeItemIndex >= 0 ) {
			var treeChildren = document.getElementById("treechildren");
			if ( treeChildren != null ) {
				if ( selectedTreeItemIndex >= treeChildren.childNodes.length ) {
					selectedTreeItemIndex = treeChildren.childNodes.length - 1;
				} 
				var selectedTreeItem = treeChildren.childNodes[selectedTreeItemIndex];
				
				var reminderDateTime = selectedTreeItem.childNodes[0].getAttribute(REMINDER_DATE_REF);	
				var reminderInstanceDate = new Date(parseInt(reminderDateTime));		
				oeDatePicker.onpopupshowing(reminderInstanceDate);
			}
		}
	}
	rmFxCore.statusSet ("");
}


function todoSelected(event) {
	if ( selectCalendarSync ) {
		var selectedTreeItemIndex = document.getElementById("todoTree").currentIndex; 
		if ( selectedTreeItemIndex >= 0 ) {
			var treeChildren = document.getElementById("todoTreechildren");
			if ( treeChildren != null ) {
				if ( selectedTreeItemIndex >= treeChildren.childNodes.length ) {
					selectedTreeItemIndex = treeChildren.childNodes.length - 1;
				} 
				if ( selectedTreeItemIndex < 0 ) {
					return;
				}
				var selectedTreeItem = treeChildren.childNodes[selectedTreeItemIndex];
				var reminderDateTime = selectedTreeItem.childNodes[0].getAttribute(REMINDER_DATE_REF);	
				if ( reminderDateTime != null  && reminderDateTime.length > 0) {
					var reminderInstanceDate = new Date(parseInt(reminderDateTime));		
					oeDatePicker.onpopupshowing(reminderInstanceDate);
				}
			}
		}
	}
	rmFxCore.statusSet (""); 
}


function reminderFox_getReminderViewAsHTMLFile() {
	var file;
	var savefilePath;
	// check if user has specified a specific file path in their preferences
	try {
		//gW_OSswitching
		savefilePath = rmFx_getStoreFile4OS();
	}
	catch ( e) {
	}
	// if not, then use default location in profile
	if ( savefilePath == null || savefilePath == "" ) {
		 file = Components.classes["@mozilla.org/file/directory_service;1"]
       		  .getService(Components.interfaces.nsIProperties)
    	      .get("ProfD", Components.interfaces.nsIFile);

	      file.append( "reminderfox" );
	      file.append( "reminderfox.ics" + ".html" );			
	}
	else {
		savefilePath = savefilePath + ".html";
		file = Components.classes["@mozilla.org/file/local;1"]
					.createInstance(Components.interfaces.nsILocalFile);
		file.initWithPath( savefilePath );
	}
	return file;
}


function doShowHTML() {
	
	var tabList = document.getElementById("tabList");	
	var tab =	tabList.selectedItem;
	var listName = tab.getAttribute( "label");
	
	var outputStr = "";
	
	outputStr += "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 // Transitional//EN\">\n";
	outputStr += "<HTML>\n";
	
	outputStr += "<HEAD>\n";
	
	outputStr += "<TITLE>" + g_reminderFoxBundle.getString("rf.title") + "</TITLE>\n";
	//outputStr += "<link rel=\"shortcut icon\" href=\"" + REMINDER_FOX_REMIND_UNTIL_COMPLETED_IMAGE + "\" type=\"image/png\" >\n";
	outputStr += "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n";
	
	var stylesheet = reminderFox_getPreferenceValue( REMINDER_FOX_HTML_STYLESHEET_PREF );
	if ( stylesheet != null && stylesheet.length > 0 ) {  // do for showReminders too
		outputStr += "<link rel=\"stylesheet\" href=\"" + stylesheet + "\" type=\"text/css\">\n";
	}
	outputStr += "</HEAD>\n";
	outputStr += "<div id=\"main\">\n";	
	
	if ( stylesheet != null && stylesheet.length > 0 ) { // don't need title if not using styleshet 
		outputStr += "<h4>" + listName + "</h4>\n";
	}
		
	outputStr += "<BODY>\n";
	
	outputStr += "<TABLE border=\"1\">\n";
	outputStr += "<TBODY>\n";	
	outputStr += "  <TR>\n";
	
	outputStr += "    <TD>\n";
	outputStr += "      <b>" + g_reminderFoxBundle.getString("rf.html.heading.date") + "</b>\n";
	outputStr += "    </TD>\n";
	
	outputStr += "    <TD>\n";
	outputStr += "      <b>" + g_reminderFoxBundle.getString("rf.html.heading.reminder") + "</b>\n";
	outputStr += "    </TD>\n";
	
	outputStr +=  "    <TD>\n";
	outputStr += "      <b>" + g_reminderFoxBundle.getString("rf.html.heading.time") + "</b>\n";
	outputStr += "    </TD>\n";	
	
	outputStr += "  </TR>\n";		

	var i;
	var item;
	var row;
	var dateCell;
	var dateCellLabel	
	var descCell;
	var descCellLabel;
	var timeCell;
	var timeCellLabel;	
		
	var treeChildren = document.getElementById("treechildren");
	var treeitems = treeChildren.childNodes;
	
	
	var indices = null;
	var multipleRemindersSelected = getAllSelectedReminderIndices();
	if ( multipleRemindersSelected.length > 1 ) {
		indices = multipleRemindersSelected;
	}
	else {
		indices = new Array(treeitems.length);
		for (  i = 0; i < treeitems.length; i++ ) {
			indices[i] = i;
		}
	}

	for ( i=0; i < indices.length; i++) { 
		item = treeitems[indices[i]];
		row = item.childNodes[0];
		dateCell = row.childNodes[0];
		dateCellLabel = dateCell.getAttribute("label");		
		dateCellLabel = dateCellLabel.replace(new RegExp(/ /g),"&nbsp;");  
		descCell = row.childNodes[1];
		descCellLabel = descCell.getAttribute("label");
		timeCell = row.childNodes[2];
		timeCellLabel = timeCell.getAttribute("label");		
		timeCellLabel = timeCellLabel.replace(new RegExp(/ /g),"&nbsp;");  
		
		var important = descCell.getAttribute("properties" ) == "important" || 
			descCell.getAttribute("properties" ) == "imporantCompleteTextToday" || 		
			descCell.getAttribute( "properties" ) == "imporantCompleteText";
		var completed = descCell.getAttribute("properties" ) == "completeText" ||
			descCell.getAttribute("properties" ) == "imporantCompleteTextToday" ||
			descCell.getAttribute( "properties" ) == "imporantCompleteText";			
					
		outputStr +=  "  <TR>\n";

		outputStr +=  "    <TD>\n";
		if ( important ) {
			outputStr +=  "    <FONT color=\"FF0000\">\n";
		}	
		if ( completed ) {
			outputStr +=  "    <del>\n";
		}
		outputStr +=  "      " ;
		outputStr += dateCellLabel + "\n";
		if ( important ) {
			outputStr +=  "    </FONT>\n";
		}	
		if ( completed ) {
			outputStr +=  "    </del>\n";
		}
		outputStr +=  "    </TD>\n";
		
		outputStr +=  "    <TD>\n";
		if ( important ) {
			outputStr +=  "    <FONT color=\"FF0000\">\n";
		}	
		if ( completed ) {
			outputStr +=  "    <del>\n";
		}		
		outputStr +=  "      " ;
		outputStr +=  descCellLabel + '\n';
		if ( important ) {
			outputStr +=  "    </FONT>\n";
		}			
		if ( completed ) {
			outputStr +=  "    </del>\n";
		}
		outputStr +=  "    </TD>\n";		
		
		outputStr +=  "    <TD>\n";
		if ( important ) {
			outputStr +=  "    <FONT color=\"FF0000\">\n";
		}	
		if ( completed ) {
			outputStr +=  "    <del>\n";
		}		
		outputStr +=  "      " ;
		outputStr +=  timeCellLabel + '\n';
		if (important ) {
			outputStr +=  "    </FONT>\n";
		}		
		if ( completed ) {
			outputStr +=  "    </del>\n";
		}
		outputStr +=  "    </TD>\n";				

		
		outputStr +=  "  </TR>\n";	

		// output notes if available
		// want to replace in notes: ("\n", "<BR/>") to get line breaks
		var reminder =  reminderFox_getRemindersById( row.getAttribute(REMINDER_ID_REF), getCurrentReminderList() );
	 	if ( reminder != null  && reminder.notes != null ) { 		
			outputStr +=  "  <TR>\n";
			
			outputStr +=  "    <TD>\n";
			outputStr +=  "    </TD>\n";
			
			outputStr +=  "    <TD>\n";
			var notes = reminder.notes;
			notes = notes.replace(new RegExp(/\n/g),"<BR/>");  	
			outputStr +=  "      " + notes;
			
			outputStr +=  "    </TD>\n";		
			
			outputStr +=  "    <TD>\n";
			outputStr +=  "    </TD>\n";
			
			outputStr +=  "    <TD>\n";
			outputStr +=  "    </TD>\n";			
			
			outputStr +=  "  </TR>\n";	
	 	}		
		
	}	
	
	outputStr +=  " </TBODY>\n";
	outputStr +=  "</TABLE>\n";
	outputStr +=  "</BODY>\n";
	outputStr += "</div>\n"
	outputStr +=  "</HTML>\n";
	
	var file = reminderFox_getReminderViewAsHTMLFile();
	
	if ( file.exists() == false ) {
		file.create( Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 420 );
	}

	reminderFox_writeStringToFile(outputStr, file, true);

	var tempURL = "file:///" + file.path; 
	reminderFox_openURL(tempURL );
	//file.remove(false);  // can't remove here as it can be removed before the browser opens (in Thunderbird case)
}

function doShowToDosHTML() {
	var outputStr = "";
		
	// get list name for title
	var tabList = document.getElementById("tabList");	
	var tab =	tabList.selectedItem;
	var listName = tab.getAttribute( "label");

	outputStr += "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 // Transitional//EN\">\n";

	outputStr += "<HTML>\n";
	outputStr += "<HEAD>\n";
	outputStr += "<TITLE>" +g_reminderFoxBundle.getString("rf.title") + " - " + listName + "</TITLE>\n";
	outputStr += "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n";
	
	var stylesheet = reminderFox_getPreferenceValue( REMINDER_FOX_HTML_STYLESHEET_PREF );
	if ( stylesheet != null && stylesheet.length > 0 ) {  
		outputStr += "<link rel=\"stylesheet\" href=\"" + stylesheet + "\" type=\"text/css\">\n";
	}
	outputStr += "</HEAD>\n";
	
	outputStr += "<div id=\"main\">\n";	
	
	if ( stylesheet != null && stylesheet.length > 0 ) { // don't need title if not using styleshet 
		outputStr += "<h4>" + listName + "</h4>\n";
	}
		
	outputStr += "<BODY>\n";
	outputStr += "<TABLE border=\"1\">\n";
	outputStr += " <TBODY>\n";	
	
	outputStr +=  "  <TR>\n";
	
	outputStr +=  "    <TD>\n";		
	outputStr +=  "      <b>" + g_reminderFoxBundle.getString("rf.html.heading.todo.number") + "</b>\n";
	outputStr +=  "    </TD>\n";
	
	outputStr +=  "    <TD>\n";	
	outputStr +=  "      <b>" + listName + "</b>\n";
	outputStr +=  "    </TD>\n";
	
	outputStr +=  "    <TD>\n";
	outputStr +=  "      <b>" + g_reminderFoxBundle.getString("rf.html.heading.date") + "</b>\n";
	outputStr +=  "    </TD>\n";	
	
	outputStr +=  "    <TD>\n";
	outputStr +=  "      <b>" + g_reminderFoxBundle.getString("rf.html.heading.time") + "</b>\n";
	outputStr +=  "    </TD>\n";		
	
	outputStr +=  "  </TR>\n";		

	var i;
	var item;
	var row;
	var dateCell;
	var dateCellLabel	
	var descCell;
	var descCellLabel;
	var timeCell;
	var timeCellLabel;	
		
	var treeChildren = document.getElementById("todoTreechildren");
	var treeitems = treeChildren.childNodes;
	
	
	
	var indices = null;
	var multipleTodosSelected = getAllSelectedTodoIndices();
	if ( multipleTodosSelected.length > 1 ) {
		indices = multipleTodosSelected;
	}
	else {
		indices = new Array(treeitems.length);
		for (  i = 0; i < treeitems.length; i++ ) {
			indices[i] = i;
		}
	}

	for ( i=0; i < indices.length; i++) {
		item = treeitems[indices[i]];	
		row = item.childNodes[0];		
		var todo = reminderFox_getTodosById( row.getAttribute(REMINDER_ID_REF),  getCurrentTodoList() );		
		
		dateCell = row.childNodes[0];
		dateCellLabel = dateCell.getAttribute("label");
		dateCellLabel = dateCellLabel.replace(new RegExp(/ /g),"&nbsp;");  
		descCell = row.childNodes[1];
		descCellLabel = descCell.getAttribute("label");
		timeCell = row.childNodes[2];
		timeCellLabel = timeCell.getAttribute("label");		
		timeCellLabel = timeCellLabel.replace(new RegExp(/ /g),"&nbsp;");  
		
		var important = descCell.getAttribute("properties" ) == "important" ||
			descCell.getAttribute( "properties" ) == "imporantCompleteText";
		var completed = descCell.getAttribute("properties" ) == "completeText" ||
			descCell.getAttribute( "properties" ) == "imporantCompleteText";						
		
		outputStr +=  "  <TR>\n";
				
		outputStr +=  "    <TD>\n";
		if ( important ) {
			outputStr +=  "    <FONT color=\"FF0000\">\n";
		}			
		if ( completed ) {
			outputStr +=  "    <del>\n";
		}		
		outputStr +=  "      ";		
		outputStr += (i+1) + "\n";  // +1 so we start with a 1-based index
		if ( important ) {
			outputStr +=  "    </FONT>\n";
		}		
		if ( completed ) {
			outputStr +=  "    </del>\n";
		}
		outputStr +=  "    </TD>\n";
		
		outputStr +=  "    <TD>\n";
		if ( important)  {
			outputStr +=  "    <FONT color=\"FF0000\">\n";
		}			
		if ( completed ) {
			outputStr +=  "    <del>\n";
		}		
		outputStr +=  "      " ;
		outputStr +=  descCellLabel + '\n';
		if ( important ) {
			outputStr +=  "    </FONT>\n";
		}			
		if ( completed ) {
			outputStr +=  "    </del>\n";
		}		
		outputStr +=  "    </TD>\n";		
		
		outputStr +=  "    <TD>\n";
		if ( important ) {
			outputStr +=  "    <FONT color=\"FF0000\">\n";
		}	
		if ( completed ) {
			outputStr +=  "    <del>\n";
		}		
		outputStr +=  "      " ;
		if ( dateCellLabel == "" ) {
			dateCellLabel = "&nbsp;";
		}
		outputStr += dateCellLabel + "\n";
		if ( important ) {
			outputStr +=  "    </FONT>\n";
		}				
		if ( completed ) {
			outputStr +=  "    </del>\n";
		}		
		outputStr +=  "    </TD>\n";		
		
		outputStr +=  "    <TD>\n";
		if ( important ) {
			outputStr +=  "    <FONT color=\"FF0000\">\n";
		}	
		if ( completed ) {
			outputStr +=  "    <del>\n";
		}		
		outputStr +=  "      " ;
		if ( timeCellLabel == "" ) {
			timeCellLabel = "&nbsp;";
		}		
		outputStr +=  timeCellLabel + '\n';
		if (important ) {
			outputStr +=  "    </FONT>\n";
		}		
		if ( completed ) {
			outputStr +=  "    </del>\n";
		}				
		outputStr +=  "    </TD>\n";				
		
		outputStr +=  "  </TR>\n";	
		
		// output notes if available
		// want to replace in notes: ("\n", "<BR/>") to get line breaks
			
	 	if ( todo != null  && todo.notes != null ) { 		
			outputStr +=  "  <TR>\n";
			
			outputStr +=  "    <TD>\n";
			outputStr +=  "    </TD>\n";
			
			outputStr +=  "    <TD>\n";

			var notes = todo.notes;
			notes = notes.replace(new RegExp(/\n/g),"<BR/>");  					
			outputStr +=  "      " +notes;
			
			outputStr +=  "    </TD>\n";		
			
			outputStr +=  "    <TD>\n";
			outputStr +=  "    </TD>\n";
			
			outputStr +=  "    <TD>\n";
			outputStr +=  "    </TD>\n";			
			
			outputStr +=  "  </TR>\n";	
	 	}
		
	}	

	outputStr +=  " </TBODY>\n";
	outputStr +=  "</TABLE>\n";
	outputStr +=  "</BODY>\n";
	outputStr += "</div>\n";
	outputStr +=  "</HTML>\n";
	

	// now write file out to filesystem
	var file = reminderFox_getReminderViewAsHTMLFile();
	if ( file.exists() == false ) {
		file.create( Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 420 );
	}

	reminderFox_writeStringToFile(outputStr, file, true);

	var tempURL = "file:///" + file.path; 
	reminderFox_openURL(tempURL );	
	//file.remove(false);  // can't remove here as it can be removed before the browser opens (in Thunderbird case)
}


function createCalendarReminderArray() {
	var monthArray;
	var monthDay;	
	var dayReminderArray;	
	var newDayReminder;
	var  length;
	var val;
		
	calendarReminderArray = new Array(12); 
	var reminders = getCurrentReminderList();	
	
	var currentDate = oeDatePicker.gSelectedDate;
	if ( currentDate == null ) {
		currentDate = new Date();
	}
	var	year = currentDate.getFullYear();
	
	var displayIndex = null;	//gW_getStartAndEndDates  
							    // set 	displayIndex =999 to display reminders past/future years
	var dateSpan = getStartAndEndDates(displayIndex, null, null, "reminders");
	var todaysDate = new Date();
	for( var i = 0; i < reminders.length; i++) {
		var basereminder = reminders[i];
		
		var allReminders = reminderFox_getAllRemindersInDateRange( basereminder,  dateSpan.start, dateSpan.end, false );
		var x;
		// maybe make this a method that returns start/endindex
		var startIndex = 0;
		var endIndex = 0;
		if ( allReminders.length > 0 ) {
			endIndex  = allReminders.length;
		}
		if ( allReminders.length > 0) {
			if ( SHOW_ALL_REMINDERS ) {
				startIndex = 0;
				endIndex = allReminders.length;
			}
			else if ( HIDE_ALL_REMINDERS ) {
				for ( x = 0; x < allReminders.length; x++ ) {
					if ( reminderFox_compareDates( allReminders[x].date, todaysDate) != -1 ) {
						break;
					}
				}
				// handle end case where x = length
				startIndex = x;
		
				// need to show reminders of yearly that have passed
				if ( startIndex == allReminders.length ) {				
					startIndex = allReminders.length -1;
				}
				endIndex = startIndex + 1;  
				if ( endIndex > allReminders.length )  {
					endIndex = allReminders.length;
				}
			}
			// if there's only 1 reminder and the prefs are set to show prev/next, then just ignore the check
			else if ( !(allReminders.length == 1 && REPEAT_PREVIOUS_OCCURRENCES >= 1 &&  REPEAT_UPCOMING_OCCURRENCES >=1 ) )  {			
				for ( x = 0; x < allReminders.length; x++ ) {
					if ( reminderFox_compareDates( allReminders[x].date, todaysDate) != -1 ) {
						break;
					}
				}
				
				if ( REPEAT_PREVIOUS_OCCURRENCES == -1 ) { 
					startIndex = 0;
				}
				else {
					startIndex = x - REPEAT_PREVIOUS_OCCURRENCES;
					if ( startIndex < 0 ) {
						startIndex = 0;
					}
				}
				
				if ( REPEAT_UPCOMING_OCCURRENCES == -1 ) {
					endIndex = allReminders.length;
				}
				else {
					endIndex = x + REPEAT_UPCOMING_OCCURRENCES;
					if ( endIndex > allReminders.length ) {
						endIndex = allReminders.length;
					}
				}
				
				// if the user is showing no previous occurrences, we still want to show if a previous reminder is marked as RUC
				if ( REPEAT_PREVIOUS_OCCURRENCES == 0 && 
					basereminder.remindUntilCompleted == REMINDERFOX_REMIND_UNTIL_COMPLETE_MARKED ) {
					if ( startIndex > 0  && startIndex == endIndex  ) { // eminderFox_compareDates( allReminders[x].date, todaysDate) == 1 ) {
						startIndex = startIndex - 1;														
					}					
				}								
			 }
		}
       for (  var j = startIndex; j < endIndex; j++ ) {		
			var reminder = allReminders[j];		
			reminder = reminderFox_processReminderDescription(reminder,  dateSpan.start.getFullYear(), false);	
			
			// if it's marked as RemindUntilComplete, this should be treated as Today's date			
		 	if ( reminder.remindUntilCompleted == REMINDERFOX_REMIND_UNTIL_COMPLETE_MARKED && j == startIndex ) {
		 		var todaysDate = new Date();
		 		if (  todaysDate.getFullYear() == year ) {   // only valid for current year in the calendar
			 		var ignore = false;
		 			var displayList = document.getElementById("displayType");	
					if ( displayList != null ) {	
						var displayListIndex = displayList.selectedIndex;
						// month or week
						if ( displayListIndex == 1 || displayListIndex == 2 ) {
							// if the date is outside of the selected month/week, then just show it.
							// Otherwise, go ahead and show it as Today's date.							
							if ( !( reminderFox_compareDates( todaysDate, dateSpan.start) > -1 &&
								reminderFox_compareDates( todaysDate, dateSpan.end) < 1 ) ) {
								ignore = true;
							}
						}
					}
					if ( !ignore ) {
						var origDate = reminderFox_getDateVariableString( reminder, reminder.date )
		 				reminder = reminderFox_cloneReminderFoxEvent(reminder);		 	
						reminder.date  = new Date( todaysDate.getFullYear(), todaysDate.getMonth(), todaysDate.getDate(), 
						 			reminder.date.getHours(), reminder.date.getMinutes() );	
						
						// for reminders that are passed due, show original date in summary.
						// Some users prefer the date that the reminder was set for to show
						// in the list; this is a reasonable compromise								
						reminder.summary = reminder.summary + "  [" + origDate +"]";
					}
		 		}
		 	}		 	
	
			monthArray = calendarReminderArray[reminder.date.getMonth()];
			if ( monthArray == null ) {
				monthArray = new Array(31);
				calendarReminderArray[reminder.date.getMonth()] = monthArray;
			}
				
			monthDay = reminder.date.getDate();
			dayReminderArray = monthArray[monthDay - 1];
			if ( dayReminderArray == null ) {
				dayReminderArray = new Array();
				monthArray[monthDay - 1] = dayReminderArray;
			}
			length = dayReminderArray.length;
			
			var ignoreReminder = false;
			if (HIDE_COMPLETED_ITEMS &&
				 reminderFox_isCompletedForDate( reminder, reminder.date) )  {
				ignoreReminder = true;				
			}
			if ( !ignoreReminder ) {
				dayReminderArray[length] = reminder;
			}
		}
	}
}



function createCalendarTodoArrayFiltered() {
	var monthArray;
	var monthDay;	
	var dayReminderArray;	
	var newDayReminder;
	var  length;
	var val;
		
	calendarTodoArray = new Array(12);  

	var reminders = getCurrentTodoList();	
	
	var currentDate = oeDatePicker.gSelectedDate;
	if ( currentDate == null ) {
		currentDate = new Date();
	}
	var	year = currentDate.getFullYear();
	var dateSpan = getStartAndEndDates();
	var todaysDate = new Date();
	for( var i = 0; i < reminders.length; i++) {
		var basereminder = reminders[i];
		if ( basereminder.date == null ) { 
			continue;  // if there is no date set on this todo, then ignore it
		}
		
		var allTodos = reminderFox_getAllRemindersInDateRange( basereminder,  dateSpan.start, dateSpan.end, false );
		var x;
		// maybe make this a method that returns start/endindex
		var startIndex = 0;
		var endIndex = 0;
		if ( allTodos.length > 0 ) {
			endIndex  = allTodos.length;
		}
		if ( allTodos.length > 0) {
			if ( SHOW_ALL_REMINDERS ) {
				startIndex = 0;
				endIndex = allTodos.length;
			}
			else if ( HIDE_ALL_REMINDERS ) {
				for ( x = 0; x < allTodos.length; x++ ) {
					if ( reminderFox_compareDates( allTodos[x].date, todaysDate) != -1 ) {
						break;
					}
				}
				// handle end case where x = length
				startIndex = x;
		
				// need to show reminders of yearly that have passed
				if ( startIndex == allTodos.length ) {				
					startIndex = allTodos.length -1;
				}
				endIndex = startIndex + 1;  
				if ( endIndex > allTodos.length )  {
					endIndex = allTodos.length;
				}
			}
			// if there's only 1 reminder and the prefs are set to show prev/next, then just ignore the check
			else if ( !(allTodos.length == 1 && REPEAT_PREVIOUS_OCCURRENCES >= 1 &&  REPEAT_UPCOMING_OCCURRENCES >=1 ) )  {			
				for ( x = 0; x < allTodos.length; x++ ) {
					if ( reminderFox_compareDates( allTodos[x].date, todaysDate) != -1 ) {
						break;
					}
				}
				
				if ( REPEAT_PREVIOUS_OCCURRENCES == -1 ) { 
					startIndex = 0;
				}
				else {
					startIndex = x - REPEAT_PREVIOUS_OCCURRENCES;
					if ( startIndex < 0 ) {
						startIndex = 0;
					}
				}
				
				if ( REPEAT_UPCOMING_OCCURRENCES == -1 ) {
					endIndex = allTodos.length;
				}
				else {
					endIndex = x + REPEAT_UPCOMING_OCCURRENCES;
					if ( endIndex > allTodos.length ) {
						endIndex = allTodos.length;
					}
				}							
			 }
		}
       for (  var j = startIndex; j < endIndex; j++ ) {		
			var todo = allTodos[j];			
			todo = reminderFox_processReminderDescription(todo, dateSpan.start.getFullYear(), false);	
				
			monthArray = calendarTodoArray[todo.date.getMonth()];
			if ( monthArray == null ) {
				monthArray = new Array(31);
				calendarTodoArray[todo.date.getMonth()] = monthArray;
			}
				
			monthDay = todo.date.getDate();
			dayReminderArray = monthArray[monthDay - 1];
			if ( dayReminderArray == null ) {
				dayReminderArray = new Array();
				monthArray[monthDay - 1] = dayReminderArray;
			}
			length = dayReminderArray.length;
			
			var ignoreReminder = false;			
			if (HIDE_COMPLETED_ITEMS &&
						 todo.completedDate != null ) { 
					ignoreReminder = true;			
			}
	
			if ( !ignoreReminder ) {
				dayReminderArray[length] = todo;
			}			
		}
	}
}


function createCalendarTodoArray() {
	// if filtered, then get the individual repeat instances...
	var filterIndex = getDisplayIndex("todos");
	if ( filterIndex > 0 ) {
		createCalendarTodoArrayFiltered();
		return;
	}
	
	
	var monthArray;
	var monthDay;	
	var dayReminderArray;	
	var newDayReminder;
	var  length;
	var val;

	calendarTodoArray = new Array(12);  

	var dateSpan = getStartAndEndDates();
	var allTodos = reminderFox_getAllTodosInDateRangeForGivenList(getCurrentTodoList(),   dateSpan.start, dateSpan.end );
	
   for (  var j = 0; j < allTodos.length; j++ ) {		
		var todo = allTodos[j];			
		todo = reminderFox_processReminderDescription(todo, dateSpan.start.getFullYear(), false);	
			
		monthArray = calendarTodoArray[todo.date.getMonth()];
		if ( monthArray == null ) {
			monthArray = new Array(31);
			calendarTodoArray[todo.date.getMonth()] = monthArray;
		}
			
		monthDay = todo.date.getDate();
		dayReminderArray = monthArray[monthDay - 1];
		if ( dayReminderArray == null ) {
			dayReminderArray = new Array();
			monthArray[monthDay - 1] = dayReminderArray;
		}
		length = dayReminderArray.length;
		
		var ignoreReminder = false;			
		if (HIDE_COMPLETED_ITEMS &&
					 todo.completedDate != null ) { 
				ignoreReminder = true;			
		}

		if ( !ignoreReminder ) {
			dayReminderArray[length] = todo;
		}		
	}
}


function reminderFox_getAddTimeString( reminder ) {
	var timeString = null;
	if ( !reminder.allDayEvent ) {
		try {
			var hours = reminder.date.getHours();
			
			var AMorPM = REMINDER_FOX_PM;				
			var use24HourTime;
			try {
				use24HourTime = reminderFox_prefs.getBoolPref(REMINDER_FOX_PREF + "." + REMINDER_FOX_USE_24_HOUR_TIME);
			} catch(e) {
			}				
			if (  use24HourTime ) {
				AMorPM = "";
				if ( hours < 10 ) {
					hours = "0" + hours;
				}
		
			}		
		
			if ( AMorPM != "" ) {
				if ( hours < 12 ) {
					AMorPM = REMINDER_FOX_AM;
				}
				if ( hours == 0 ) {
					hours = 12;
				}
				if ( hours >= 13 ) {
					hours = hours -12;
				}	
			}			

			var minutes = reminder.date.getMinutes();
			if ( minutes < 10 ) {
				minutes = "0" + minutes;
			}
							
			timeString = hours + REMINDER_FOX_TIME_DELIMITER + minutes;
			if ( AMorPM != "" ) {
				timeString = timeString + " " + AMorPM;		
			}
		}
		catch ( e ) { 
		}
	}	
	return timeString;
}

function setRemindUntilCompleteColumn( reminder, columnLabel ) {
         if ( reminder.remindUntilCompleted == REMINDERFOX_REMIND_UNTIL_COMPLETE_TO_BE_MARKED ) {
         	 columnLabel.setAttribute("src",REMINDER_FOX_REMIND_UNTIL_COMPLETED_TO_BE_MARKED_IMAGE);	
         }
         else  if ( reminder.remindUntilCompleted == REMINDERFOX_REMIND_UNTIL_COMPLETE_MARKED ) {
         	 columnLabel.setAttribute("src",REMINDER_FOX_REMIND_UNTIL_COMPLETED_IMAGE);
         }
}




function getTimeHoursFromString(time) {
	var hours = 0;
	var startindex = time.indexOf(g_reminderFoxBundle.getString("rf.add.time.delimiter") ); 
	if ( startindex != -1 ) {
		try {
			var hours = parseInt(time.substring(0, startindex ));
			var minutes =  time.substring(startindex+1, startindex + 3);
			// now trim remainder
			var remainder = time.substring( startindex + 3, time.length );
			if ( remainder != "" ) {
				remainder = reminderFox_trim( remainder );
				var AMorPM = remainder;
				if ( AMorPM.toUpperCase() == REMINDER_FOX_PM.toUpperCase() ) {
					if ( hours != 12 ) {
						hours = hours+12;
					}
				}
				else { 
					if ( hours == 12 ) {
						hours = 0;
					}
				}
			}
		}
		catch ( e ) {
		}
	}
	return hours;
}

function getTimeMinutesFromString(time) {
	var minutes = 0;
	var startindex = time.indexOf(g_reminderFoxBundle.getString("rf.add.time.delimiter") ); 
	if ( startindex != -1 ) {
		try {
			 minutes =  time.substring(startindex+1, startindex + 3);
		}
		catch ( e ) {
		}
	}
	return minutes;
}


function reminderFox_getDateVariableString(reminder, date )  {
	return reminderFox_getDateVariable( reminder, date, dateVariableString );
}

/**
 * 'View'
 *<br> 	'getStartAndEndDates' has been modified to use also with 'View'.
 *<br> 	calling parameters:
 *<br> 		displayListIndex :: day-periode, same as with getDisplayIndex()
 *<br> 		useToday ::		true== use 'TODAY' for start day of selected 'day-periode'
 *<br> 
 *<br> 	Note:  rearranging/adding the XUL items and a re-numbering has to be changed
 *<br> 			also with 'VIEW'  (rmFxViews.js) 
 */
function getStartAndEndDates(displayListIndex, useToday, showAll, remindersOrTodoString) {
	var startAndEnd = { start: null, end: null };  
	
	//  if 'View' has set the date span already, use that			//gW_getStartAndEndDates
	if 	(gRmFx_Views.cDateSpan.start != null) {
		startAndEnd.start = gRmFx_Views.cDateSpan.start;
		startAndEnd.end   = gRmFx_Views.cDateSpan.end;

//		rmFxUtil.dump2Console ('dateSpan', "StartAndEnd Dates set by 'VIEW' :" 
//	             + startAndEnd.start + " " + startAndEnd.end);
	    return startAndEnd;
	}
	//var showAll = false;
	if ( showAll ) {  // if showAll is true, we will show ALL reminders instead of just this year/month/week/etc
		// get all years (we'll just do +/- 150 to put some cap and aid performance)
		var currentyear = new Date().getFullYear();
		startAndEnd.start = new Date( currentyear - 150, 0, 1 );  // start of year
		startAndEnd.end  = new Date( currentyear + 150, 11, 31 );  // end of year
		return startAndEnd;
	}
	

	// process with the 'old' selection values  
	rmFxUtil.dump2Console ('dateSpan', "StartAndEnd Dates 'displayListIndex' :" 
            + displayListIndex + "  useToday:" + useToday);

	var year;
	var month;
	var day;
	if ( oeDatePicker.gSelectedDate != null ) {
		year = oeDatePicker.gSelectedDate.getFullYear();
		month = oeDatePicker.gSelectedDate.getMonth();
		day = oeDatePicker.gSelectedDate.getDate();
	}
	if ( year == null ) {
		year = new Date().getFullYear();
		month = new Date().getMonth();
		day = new Date().getDate();
		
	}	 
 
	
// gW_VIEW	<<--
//	var displayListIndex = getDisplayIndex(remindersOrTodoString);
	if (displayListIndex == null) {
		displayListIndex = getDisplayIndex(remindersOrTodoString);
	}
	if (useToday == true) {
		year = new Date().getFullYear();
		month = new Date().getMonth();
		day = new Date().getDate();
	}
// gW_VIEW  -->>	
	
	// year
	if ( displayListIndex == 0 ) {
		startAndEnd.start = new Date( year, 0, 1 );  // start of year
		startAndEnd.end  = new Date( year, 11, 31 );  // end of year
	}
	// month
	else if ( displayListIndex == 1 ) {
		var endDay = reminderFox_getValidDateForMonth( year, month, 31 );
		startAndEnd.start = new Date( year, month, 1 );  // start of year
		startAndEnd.end  = new Date( year, month, endDay );  // end of year
	}
	// week
	else if ( displayListIndex == 2 ) {
		// get start of the week
		var start = new Date( year, month, day ); 			
		startAndEnd.start = reminderFox_getThisDayFromCurrentDate( start, 0);	
		
		// get end of the week
		var end = new Date( year, month, day );
		startAndEnd.end  = reminderFox_getThisDayFromCurrentDate( end, 6);
		
		// if the start date is before this year, just use this year as start
		var startOfYear = new Date( year, 0, 1 );  // start of year
		if ( reminderFox_compareDates( startAndEnd.start, startOfYear) == -1 ) {
			startAndEnd.start = startOfYear;
		}
		// if the end date goes beyond this year, use the end of year as the stopping point
		var endOfYear =  new Date( year, 11, 31 );  // end of year
		if ( reminderFox_compareDates( startAndEnd.end, endOfYear) == 1 ) {
			startAndEnd.end = endOfYear;
		}
	}
	// day
	else if ( displayListIndex == 3 ) {
		startAndEnd.start = new Date( year, month, day );  // start of year
		startAndEnd.end  = new Date( year, month, day );  // end of year
	}
	// next week
	else if ( displayListIndex == 4 ) {
		var todaysDate = new Date();
		startAndEnd.start = todaysDate;
		startAndEnd.end  = new Date( todaysDate.getFullYear(), todaysDate.getMonth(), todaysDate.getDate() + 7 );  // end 7 days from now
		
		// if the end date goes beyond this year, use the end of year as the stopping point
		var endOfYear =  new Date( year, 11, 31 );  // end of year
		if ( reminderFox_compareDates( startAndEnd.end, endOfYear) == 1 ) {
			startAndEnd.end = endOfYear;
		}
		
	}
	// next two weeks
	else if ( displayListIndex == 5 ) {		
		var todaysDate = new Date();
		startAndEnd.start = todaysDate;
		startAndEnd.end  = new Date( todaysDate.getFullYear(), todaysDate.getMonth(), todaysDate.getDate() + 14 );  // end 7 days from now
		
		// if the end date goes beyond this year, use the end of year as the stopping point
		var endOfYear =  new Date( year, 11, 31 );  // end of year
		if ( reminderFox_compareDates( startAndEnd.end, endOfYear) == 1 ) {
			startAndEnd.end = endOfYear;
		}
	}
	// all upcoming
	else if ( displayListIndex == 6 ) {			
		var todaysDate = new Date();
		startAndEnd.start = todaysDate;
		startAndEnd.end  = new Date( todaysDate.getFullYear(), 11, 31 );  // end to the end of the year
	}
	
	if ( startAndEnd.start == null ) {
		startAndEnd.start = new Date( year, 0, 1 );  // start of year
		startAndEnd.end  = new Date( year, 11, 31 );  // end of year
	}

//	rmFxUtil.dump2Console ('dateSpan', "getStartAndEndDates :" 
//            + displayListIndex + "  " + startAndEnd.start + " " + startAndEnd.end);

    return startAndEnd;
}

function createListItem(baseReminder) {
	var lastListIndex = 0;
	var once = document.getElementById("occurrence");
	var treeChildren = document.getElementById("treechildren");
	var dateSpan = getStartAndEndDates();
	var year;
	if ( oeDatePicker.gSelectedDate != null ) {
		year = oeDatePicker.gSelectedDate.getFullYear();
	}
	if ( year == null ) {
		year = new Date().getFullYear();
	}	 
	var todaysDate = new Date();
	var allReminders = reminderFox_getAllRemindersInDateRange( baseReminder,  dateSpan.start, dateSpan.end, false );
	
	var startIndex = 0;
	var endIndex = 0;
	if ( allReminders.length > 0 ) {
		endIndex  = allReminders.length;
	}
	if ( allReminders.length > 0) {
		if ( SHOW_ALL_REMINDERS ) {
			startIndex = 0;
			endIndex = allReminders.length;
		}
		else if ( HIDE_ALL_REMINDERS ) {
			for ( var x = 0; x < allReminders.length; x++ ) {
				if ( reminderFox_compareDates( allReminders[x].date, todaysDate) != -1 ) {
					break;
				}
			}
			startIndex = x;	
			// need to show reminders of yearly that have passed
			if ( startIndex == allReminders.length ) {				
				startIndex = allReminders.length -1;
			}
		}

		// if there's only 1 reminder and the prefs are set to show prev/next, then just ignore the check
		else if ( !(allReminders.length == 1 && REPEAT_PREVIOUS_OCCURRENCES >= 1 &&  REPEAT_UPCOMING_OCCURRENCES >=1 ) )  {			
			for ( var x = 0; x < allReminders.length; x++ ) {
				if ( reminderFox_compareDates( allReminders[x].date, todaysDate) != -1 ) {
					break;

				}
			}
			if ( REPEAT_PREVIOUS_OCCURRENCES == -1 ) {
				startIndex = 0;
			}
			else {
				startIndex = x - REPEAT_PREVIOUS_OCCURRENCES;
				if ( startIndex < 0 ) {
					startIndex = 0;
				}
			}
			
			if ( REPEAT_UPCOMING_OCCURRENCES == -1 ) {
				endIndex = allReminders.length;
			}
			else {
				endIndex = x + REPEAT_UPCOMING_OCCURRENCES;
				if ( endIndex > allReminders.length ) {
					endIndex = allReminders.length;
				}
			}
		 }
	}
      
   for (  var j = startIndex; j < endIndex; j++ ) {			
		var treeSelection;
		var value ;
		var tree;	
		var boxobject;
		var first;
		var last;
		var previousReminderOffset ;		

		var newItem = document.createElement("treeitem");
		var newRow = document.createElement("treerow");
		newRow.setAttribute( REMINDER_ID_REF, baseReminder.id );
		var newDateLabel = document.createElement("treecell");
		var newDescLabel = document.createElement("treecell");
		
		newItem.appendChild(newRow);
		newRow.appendChild(newDateLabel);
		newRow.appendChild(newDescLabel);
		var isImportant = false;	
		
		var reminder = allReminders[j];		
		reminder = reminderFox_processReminderDescription(reminder, year, false);		
		
		// if it's marked as RemindUntilComplete, this should be treated as Today's date
	 	if ( reminder.remindUntilCompleted == REMINDERFOX_REMIND_UNTIL_COMPLETE_MARKED && j == startIndex ) {
	 		if (  todaysDate.getFullYear() == year ) {   // only valid for current year in the calendar
	 			// if the Filter is applied, don't show as today's date if it's another selected month/week
	 			var ignore = false;
	 		
				var displayListIndex = getDisplayIndex("reminders");
				// month or week
				if ( displayListIndex == 1 || displayListIndex == 2 ) {
					// if the date is outside of the selected month/week, then just show it.
					// Otherwise, go ahead and show it as Today's date.							
					if ( !( reminderFox_compareDates( todaysDate, dateSpan.start) > -1 &&
						reminderFox_compareDates( todaysDate, dateSpan.end) < 1 ) ) {
						ignore = true;
					}
				}
				if ( !ignore ) {
 					reminder = reminderFox_cloneReminderFoxEvent(reminder);
					reminder.date  = new Date( todaysDate.getFullYear(), todaysDate.getMonth(), todaysDate.getDate(), 
				 			reminder.date.getHours(), reminder.date.getMinutes() );	
				}
				
			}
	 	}
	
		var dayVal = reminder.date.getDate();
		if ( calendarReminderArray == null ) { 
			createCalendarReminderArray();		
		}
		var monthArray = calendarReminderArray[reminder.date.getMonth()];
		if ( monthArray == null ) {
			monthArray = new Array(31);
			calendarReminderArray[reminder.date.getMonth()] = monthArray;
		}
	
		var dayReminderArray = monthArray[dayVal - 1];
		if ( dayReminderArray == null ) {
			dayReminderArray = new Array();
			monthArray[dayVal - 1] = dayReminderArray;
		}

		var  length = dayReminderArray.length;
		dayReminderArray[length] = reminder;

		if ( useDefaultDate ) {
			var monthAsText = reminderFox_getMonthAsText(reminder.date.getMonth());		
			newDateLabel.setAttribute("label", monthAsText + " " + dayVal);
		}
		else {
			newDateLabel.setAttribute("label", reminderFox_getDateVariableString( reminder, reminder.date) );
		}
		newRow.setAttribute( REMINDER_DATE_REF, reminder.date.getTime() );
		
		newDescLabel.setAttribute("label", reminder.summary);	
		var newTimeLabel = document.createElement("treecell");
		newRow.appendChild(newTimeLabel);		
		
		var newCompletedDateLabel = document.createElement("treecell");
		newRow.appendChild(newCompletedDateLabel);				
		
		var newRepeatLabel = document.createElement("treecell");
		newRow.appendChild(newRepeatLabel);
		
		var newCompleteLabel = document.createElement("treecell");
		newRow.appendChild(newCompleteLabel);
		
		var newRemindUntilCompletedLabel = document.createElement("treecell");
		newRow.appendChild(newRemindUntilCompletedLabel);
		
		var newNotesLabel = document.createElement("treecell");
		newRow.appendChild(newNotesLabel);	
		
		var alarmLabel = document.createElement("treecell");
		newRow.appendChild(alarmLabel);		
		
		var categoriesLabel = document.createElement("treecell");
		newRow.appendChild(categoriesLabel);			
		
		var endDateLabel = document.createElement("treecell");
		newRow.appendChild(endDateLabel);		
	
		 var isToday = reminderFox_compareDates( reminder.date, todaysDate) == 0 ;
		 var isImportant = reminder.priority == REMINDER_PRIORITY_IMPORTANT;
		 var isCompleted =  reminderFox_isCompletedForDate( reminder, reminder.date);
         
		setTextProperties( isToday, isImportant, isCompleted, newDateLabel, newDescLabel, newTimeLabel );		     
	         
         if (isCompleted )  {
        	 newCompleteLabel.setAttribute("src",REMINDER_FOX_COMPLETED_IMAGE);		

			if ( useDefaultDate ) {
				var monthAsText = reminderFox_getMonthAsText(reminder.completedDate.getMonth());		
				newCompletedDateLabel.setAttribute("label", monthAsText + " " + reminder.completedDate.getDate());
			}
			else {
				newCompletedDateLabel.setAttribute("label", reminderFox_getDateVariableString( reminder, reminder.completedDate ) );
			}
        }
        
		
		if ( reminder.endDate != null ) {
			var myEndDate = new Date( reminder.date.getTime() + reminder.durationTime );
			if ( reminder.allDayEvent ) {
				myEndDate.setDate( myEndDate.getDate() -1 ); // all-day offset
			}
			if ( useDefaultDate ) {
				var monthAsText = reminderFox_getMonthAsText(myEndDate.getMonth());		
				endDateLabel.setAttribute("label", monthAsText + " " + myEndDate.getDate());
			}
			else {
				endDateLabel.setAttribute("label", reminderFox_getDateVariableString( reminder, myEndDate ) );
			}
		}
	     
	     setRemindUntilCompleteColumn( reminder, newRemindUntilCompletedLabel );


		if ( reminder.allDayEvent ) {
			newTimeLabel.setAttribute("label", REMINDER_FOX_TIME_ALL_DAY_LABEL);
		}
		else {
			var time = reminderFox_getAddTimeString(reminder);
			if ( time == null ) {
				newTimeLabel.setAttribute("label", REMINDER_FOX_TIME_ALL_DAY_LABEL);
			}
			else {			
				newTimeLabel.setAttribute("label", time);
			}
		}
		
		if ( reminder.recurrence.type  == REMINDER_RECURRENCE_YEARLY ) {
			newRepeatLabel.setAttribute("label", REPEAT_LABEL_YEARLY);
		}
		else if ( reminder.recurrence.type  == REMINDER_RECURRENCE_YEARLY_DAY ) {
			newRepeatLabel.setAttribute("label", REPEAT_LABEL_YEARLY_DAY);
		}		
		else 	if ( reminder.recurrence.type  == REMINDER_RECURRENCE_MONTHLY_DATE ) {
			newRepeatLabel.setAttribute("label", REPEAT_LABEL_MONTHLY);
		}
		else if ( reminder.recurrence.type  == REMINDER_RECURRENCE_MONTHLY_DAY ) {
			newRepeatLabel.setAttribute("label", REPEAT_LABEL_MONTHLY_DAY);
		}
		else	if ( reminder.recurrence.type  == REMINDER_RECURRENCE_WEEKLY ) {		
			newRepeatLabel.setAttribute("label", REPEAT_LABEL_WEEKLY);
		}
		else	if ( reminder.recurrence.type  == REMINDER_RECURRENCE_DAILY ) {		
	     	newRepeatLabel.setAttribute("label", REPEAT_LABEL_DAILY);
		}					
		else {		
			newRepeatLabel.setAttribute("label", REPEAT_LABEL_NONE);
		}		
		
	  	if ( reminder.notes != null ) {
     		newNotesLabel.setAttribute("src",REMINDER_FOX_NOTES_IMAGE);			
     	}     
     	
  		if ( reminder.alarm != null ) {
  			
  			// actually could check if snooze time is less than reminder's date...  if so don't show it (the snooze has passed?)
  			if ( reminder.snoozeTime != null && !isCompleted ) { 
  				alarmLabel.setAttribute("src",REMINDER_FOX_ALARM_SNOOZE_IMAGE);		
  			}
  			else {
     			alarmLabel.setAttribute("src",REMINDER_FOX_ALARM_IMAGE);			
  			}
     	}         	
     	     	
     	if ( reminder.categories != null ) {
     		categoriesLabel.setAttribute("label", reminder.categories);
     		// TODO:
     		//newDescLabel.setAttribute( "style", "color: #F6F9ED" );
     	}
     	
     	if (reminderFox_isMailEvent(reminder) ) {
     		var newMailLabel = document.createElement("treecell");
			newRow.appendChild(newMailLabel);	
     		newMailLabel.setAttribute("src",REMINDER_FOX_MAIL_IMAGE);			
     	}
     	
   
     	
		// Figure out where to put the new item in sorted list
		var treeitems = treeChildren.childNodes;
		var added = false;
		
		for (var i=lastListIndex; i < treeitems.length; i++) {
			var item = treeitems[i];
			var row = item.childNodes[0];
			var reminderDateTime = row.getAttribute(REMINDER_DATE_REF);	
			var reminderInstanceDate = new Date(parseInt(reminderDateTime));		
			
			var timeLabel = row.childNodes[2].getAttribute("label");			
			var allDay = timeLabel == REMINDER_FOX_TIME_ALL_DAY_LABEL;
			
			if (reminderInstanceDate.getMonth() > reminder.date.getMonth() || (reminderInstanceDate.getMonth() == reminder.date.getMonth() && dayVal <= reminderInstanceDate.getDate() ) ) {	
				if (reminderInstanceDate.getMonth() == reminder.date.getMonth() && reminderInstanceDate.getDate() == dayVal) {
					if ( reminder.allDayEvent && !allDay ) {
						continue;
					}
					else if ( !reminder.allDayEvent && allDay ) {
						// adding hourly reminder; let's add it
					}
					else if ( !reminder.allDayEvent && !allDay ) {
						// two hourly events.  Let's compare the times.
						var currentHours = getTimeHoursFromString(timeLabel);
						var currentMinutes = getTimeMinutesFromString(timeLabel);
						if ( reminder.date.getHours() > currentHours ) {
							continue;
						}
						else if ( reminder.date.getHours() == currentHours &&
							reminder.date.getMinutes() > currentMinutes ) {
								continue;
						}
					}
					else if ( !isImportant ) {
						// if this reminder is not marked as important, add to the 
						// end of the list of today's reminders
						continue;
					}
				}
				treeChildren.insertBefore(newItem, item);
				added = true;
			
				// highlight the newly added reminder in the list
				treeSelection = document.getElementById("reminderTree").view.selection;	
				if ( selectCalendarSync ) {
						try {
							treeSelection.select(i);
						}
						catch( e ) {
							reminderFox_logMessageLevel( "Error in selectReminderById1: " +
									e.message   , REMINDER_FOX_LOG_LEVEL_INFO);  //TODO
							reminderFox_logMessageLevel( "Error in selectReminderById1: " +
									e.message   , REMINDER_FOX_LOG_LEVEL_DEBUG);  //TODO
						}
						// make sure that newly selected row is shown in scroll pane
						value = document.getElementById("treeparent").value;
						tree = document.getElementById("reminderTree");					
						boxobject = tree.boxObject;
						boxobject.QueryInterface(Components.interfaces.nsITreeBoxObject);
						
						first = boxobject.getFirstVisibleRow();
						last = boxobject.getLastVisibleRow();
						if ( i < first || i > last ) {	
							boxobject.scrollToRow(treeitems.length - 1);
							boxobject.scrollToRow(treeitems.length - 9);
						}
											
						previousReminderOffset = 3;
						if ( i < previousReminderOffset ) { 
							boxobject.ensureRowIsVisible(i);
						}
						else {
							boxobject.ensureRowIsVisible(i  - previousReminderOffset);
						}						
				}
				lastListIndex = i;
				break;
			}
		}
			
		if (!added){		
			treeChildren.appendChild(newItem);
			// highlight the newly added reminder in the list
			treeSelection = document.getElementById("reminderTree").view.selection;	
			if ( selectCalendarSync ) {
				treeSelection.select(treeitems.length - 1);
				// make sure that newly selected row is shown in scroll pane
				value = document.getElementById("treeparent").value;
				tree = document.getElementById("reminderTree");					
				boxobject = tree.boxObject;
				boxobject.QueryInterface(Components.interfaces.nsITreeBoxObject);
				
				first = boxobject.getFirstVisibleRow();
				last = boxobject.getLastVisibleRow();
				if ( i < first || i > last ) {	
					boxobject.scrollToRow(treeitems.length - 1);			
					boxobject.scrollToRow(treeitems.length - 9);
				}
				
				previousReminderOffset = 3;
				if ( i < previousReminderOffset ) { 
					boxobject.ensureRowIsVisible(i);
				}
				else {
					boxobject.ensureRowIsVisible(i  - previousReminderOffset);
				}					
			}		
		}
		
		if ( isTabSorted() ) {
			removeAllListItems( true, false );
			fillList( true, false);			
		}
		
	}
}
 

function setTextProperties( isToday, isImportant, isCompleted, newDateLabel, newDescLabel, newTimeLabel ) {
	if ( reminderFox_highlightTodayPreference && isToday && isImportant && isCompleted ) {
		newDateLabel.setAttribute("properties", "imporantCompleteTextToday");
		newDescLabel.setAttribute("properties", "imporantCompleteTextToday");
        newTimeLabel.setAttribute("properties", "imporantCompleteTextToday");
	}
	else if ( reminderFox_highlightTodayPreference && isToday && isImportant ) {
		newDateLabel.setAttribute("properties", "imporantToday");
		newDescLabel.setAttribute("properties", "imporantToday");
        newTimeLabel.setAttribute("properties", "imporantToday");
	}
	else if ( reminderFox_highlightTodayPreference && isToday && isCompleted ) {
		newDateLabel.setAttribute("properties", "todayCompleteText");	
		newDescLabel.setAttribute("properties", "todayCompleteText");
        newTimeLabel.setAttribute("properties", "todayCompleteText");	
	}
	else if ( reminderFox_highlightTodayPreference && isToday ) {
		newDateLabel.setAttribute("properties", "today");
		newDescLabel.setAttribute("properties", "today"); 
        newTimeLabel.setAttribute("properties", "today");
	}
	else if ( isImportant && isCompleted ) {
		newDateLabel.setAttribute("properties", "imporantCompleteText");		
		newDescLabel.setAttribute("properties", "imporantCompleteText");
        newTimeLabel.setAttribute("properties", "imporantCompleteText");
	}
	else if ( isImportant ) {
		newDateLabel.setAttribute("properties", "important");		
		newDescLabel.setAttribute("properties", "important");
        newTimeLabel.setAttribute("properties", "important");
	}
	else if ( isCompleted ) {
		newDateLabel.setAttribute("properties", "completeText");		
		newDescLabel.setAttribute("properties", "completeText");
        newTimeLabel.setAttribute("properties", "completeText");
	}
	else {	
		newDateLabel.removeAttribute("properties");
		newDescLabel.removeAttribute("properties");
        newTimeLabel.removeAttribute("properties");
	}		
	
	
}



function eventMatchesFilterText( reminder, rmSearchText, currentSearchItemValue) {
	try {		//  'try'	to skip for invalid 'Item' description    
	  	if( currentSearchItemValue == SEARCH_ITEMS_ALL_INDEX ) {
			
			var found = false;
			for ( var i = 0; !found && i < searchItems.length; i++ ) {
				if ( i != SEARCH_ITEMS_ALL_INDEX ) {
					if( reminder[searchItems[i]] != null ) {  // no match
						var attributeValue = reminder[searchItems[i]].toLowerCase();
				        if (searchItems[i] == "categories") {
				            attributeValue = reminderFox_unEscapeCommas(attributeValue);
				        }  
			            if (attributeValue.search(rmSearchText) != -1) {
							found = true;
			            }
					}
				}
			}
			if ( !found ) { 
				return false;  // no matches
			}
		}
		else {
			if( reminder[searchItems[currentSearchItemValue]] == null ) {  // no match
				return false;
			}
		   var attributeValue = reminder[searchItems[currentSearchItemValue]].toLowerCase();
	        if (searchItems[currentSearchItemValue] == "categories") {
	            attributeValue = reminderFox_unEscapeCommas(attributeValue);
	        }  
            if (attributeValue.search(rmSearchText) == -1) {
                return false;
            }
		}
	} catch (e)  { return};
	return true;
}

function createListItemSorted(reminder, todaysDate) {
//gW View 2008-10-15
	if (rmFx_ViewThis(reminder, "reminders") == 0)  {return};

	if ( isListFiltered( )) {			 
		var rmSearchText =lastRmSearchText.toLowerCase();  
		if ( !eventMatchesFilterText( reminder, rmSearchText, currentRmSearchItemValue) ) {
			return; 
		}
	}
	
	var once = document.getElementById("occurrence");
	var treeChildren = document.getElementById("treechildren");

	var newItem = document.createElement("treeitem");
	var newRow = document.createElement("treerow");
	newRow.setAttribute( REMINDER_ID_REF, reminder.id );
	
	var newDateLabel = document.createElement("treecell");
	var newDescLabel = document.createElement("treecell");
	
	newItem.appendChild(newRow);  
	newRow.appendChild(newDateLabel);
	newRow.appendChild(newDescLabel);
	
	 var isToday = reminderFox_compareDates( reminder.date, todaysDate) == 0 ;
	 var isImportant = reminder.priority == REMINDER_PRIORITY_IMPORTANT;
	 var isCompleted =  reminderFox_isCompletedForDate( reminder, reminder.date);
		
	var monthAsText = reminderFox_getMonthAsText(reminder.date.getMonth());	
	if ( useDefaultDate ) {
		newDateLabel.setAttribute("label", monthAsText + " " +  reminder.date.getDate());
	}
	else {
		newDateLabel.setAttribute("label", reminderFox_getDateVariableString( reminder, reminder.date ) );
	}	
	
	newRow.setAttribute( REMINDER_DATE_REF, reminder.date.getTime() );

	newDescLabel.setAttribute("label", reminder.summary);
			
	var newTimeLabel = document.createElement("treecell");
	newRow.appendChild(newTimeLabel);		
	
	var newCompletedDateLabel = document.createElement("treecell");
	newRow.appendChild(newCompletedDateLabel);				
			
	
	var newRepeatLabel = document.createElement("treecell");
	newRow.appendChild(newRepeatLabel);
	
	var newCompleteLabel = document.createElement("treecell");
	newRow.appendChild(newCompleteLabel);
	
	var newRemindUntilCompletedLabel = document.createElement("treecell");
	newRow.appendChild(newRemindUntilCompletedLabel);
	
	var newNotesLabel = document.createElement("treecell");
	newRow.appendChild(newNotesLabel);	
	
	var alarmLabel = document.createElement("treecell");
	newRow.appendChild(alarmLabel);			
	
	var catLabel = document.createElement("treecell");
	newRow.appendChild(catLabel);		 	
	
	var endDateLabel = document.createElement("treecell");
	newRow.appendChild(endDateLabel);		
  
	setTextProperties( isToday, isImportant, isCompleted, newDateLabel, newDescLabel, newTimeLabel );		     
    
    if ( isCompleted )  {
	    newCompleteLabel.setAttribute("src",REMINDER_FOX_COMPLETED_IMAGE);	
		if ( useDefaultDate ) {
			var monthAsText = reminderFox_getMonthAsText(reminder.completedDate.getMonth());		
			newCompletedDateLabel.setAttribute("label", monthAsText + " " + reminder.completedDate.getDate());
		}
		else {
			newCompletedDateLabel.setAttribute("label", reminderFox_getDateVariableString( reminder, reminder.completedDate ) );
		}        	 
     }
     
		
	if ( reminder.endDate != null ) {
		var myEndDate = new Date( reminder.date.getTime() + reminder.durationTime );
		if ( reminder.allDayEvent ) {
			myEndDate.setDate( myEndDate.getDate() -1 ); // all-day offset
		}
		if ( useDefaultDate ) {
			var monthAsText = reminderFox_getMonthAsText(myEndDate.getMonth());		
			endDateLabel.setAttribute("label", monthAsText + " " + myEndDate.getDate());
		}
		else {
			endDateLabel.setAttribute("label", reminderFox_getDateVariableString( reminder, myEndDate ) );
		}
	}
     
     
	setRemindUntilCompleteColumn( reminder, newRemindUntilCompletedLabel );     
     
     if ( reminder.notes != null ) {
     	  //newNotesLabel.setAttribute("properties", "notes");
     	newNotesLabel.setAttribute("src", REMINDER_FOX_NOTES_IMAGE);			
     }     
     
  	if ( reminder.alarm != null ) {
		if ( reminder.snoozeTime != null && !isCompleted) { 
			alarmLabel.setAttribute("src",REMINDER_FOX_ALARM_SNOOZE_IMAGE);		
		}
		else {
 			alarmLabel.setAttribute("src",REMINDER_FOX_ALARM_IMAGE);			
		}	    	
     }         	
     	     
     
	if (reminderFox_isMailEvent(reminder) ) {
 		var newMailLabel = document.createElement("treecell");
		newRow.appendChild(newMailLabel);	
 		newMailLabel.setAttribute("src",REMINDER_FOX_MAIL_IMAGE);			
 	} 
 	
 	   
//gW_Categories  <<<----- 
 	if ( reminder.categories != null ) { 	
    	catLabel.setAttribute("label",reminder.categories);	

//     	    TODO:
//     		newDescLabel.removeAttribute("properties");
//     		newDescLabel.setAttribute( "style", " color: blue" );
     		//newDescLabel.setAttribute("properties", "important");

     }       	
//   ---->>>

 	
 	if ( reminder.allDayEvent ) {
		newTimeLabel.setAttribute("label", REMINDER_FOX_TIME_ALL_DAY_LABEL);
	}
	else {
		var time = reminderFox_getAddTimeString(reminder);
		if ( time == null ) {
			newTimeLabel.setAttribute("label", REMINDER_FOX_TIME_ALL_DAY_LABEL);
		}
		else {			
			newTimeLabel.setAttribute("label", time);
		}
	}
	
	if ( reminder.recurrence.type  == REMINDER_RECURRENCE_YEARLY ) {
		newRepeatLabel.setAttribute("label", REPEAT_LABEL_YEARLY);
	}
	else if ( reminder.recurrence.type  == REMINDER_RECURRENCE_YEARLY_DAY ) {
		newRepeatLabel.setAttribute("label", REPEAT_LABEL_YEARLY_DAY);
	}		
	else 	if ( reminder.recurrence.type  == REMINDER_RECURRENCE_MONTHLY_DATE ) {
		newRepeatLabel.setAttribute("label", REPEAT_LABEL_MONTHLY);
	}
	else if ( reminder.recurrence.type  == REMINDER_RECURRENCE_MONTHLY_DAY ) {
		newRepeatLabel.setAttribute("label", REPEAT_LABEL_MONTHLY_DAY);
	}
	else	if ( reminder.recurrence.type  == REMINDER_RECURRENCE_WEEKLY ) {		
		newRepeatLabel.setAttribute("label", REPEAT_LABEL_WEEKLY);
	}
	else 	if ( reminder.recurrence.type  == REMINDER_RECURRENCE_DAILY ) {
		newRepeatLabel.setAttribute("label", REPEAT_LABEL_DAILY);
	}
	else {		
		newRepeatLabel.setAttribute("label", REPEAT_LABEL_NONE);
	}		
	
	treeChildren.appendChild(newItem);		
}

function getCurrentTodoList() {
	var todosArr =	reminderFox_getReminderTodos();
	var tabList = document.getElementById("tabList");	
	var tab =	tabList.selectedItem;
	var tabIndex =	tabList.selectedIndex;
	var index = tab.id.indexOf( ':' );
	if ( tabIndex <= 1 || index == -1 ) {
		name = REMINDER_FOX_DEFAULT_TODOS_CATEGORY;
	}
	else {
		name = tab.id.substring( index +1 , tab.id.length );
	}
	var todos = todosArr[name];
	if ( todos == null ) {
		todos = new Array();
		todosArr[name] = todos;
	}
	return todos;
}

function getCurrentReminderList() {
	if ( isSubscribedCalendarTabSelected() ) {
		var subscribedCalArr =	getSubscribedCalendars();
		var tabList = document.getElementById("tabList");	
		var tab =	tabList.selectedItem;
		var tabIndex =	tabList.selectedIndex;
		var index = tab.id.indexOf( ':' );		
		name = tab.id.substring( index +1 , tab.id.length );
		
		var subscribedCal = subscribedCalArr[name];
		if ( subscribedCal == null  ) { // || subscribedCal.length == 0 ) {
			// download this subscription...
			subscribedCal = new Array();
			subscribedCalArr[name] = subscribedCal;
			// start downloading in background 
			setTimeout( reminderFox_downloadSubscribedCalendar, 1, name, subscribedCal);
		}
		return subscribedCal;
	}
	else {
		var reminders = reminderFox_getReminderEvents();	  
		return reminders;
	}	
}

function getSubscribedCalendars() {
		if ( reminderFox_subscribedCalendars == null ) {
			reminderFox_subscribedCalendars = { };
		}	
		 
		return reminderFox_subscribedCalendars;
	}
	
	
	
function reminderFox_downloadSubscribedCalendar(name, subscribedCal) {
	// sync 'em up 
	var statusTxt = document.getElementById("reminderFox-network-status");
	
	
	var subscriptions = reminderFox_getSubscriptions();	
	var url = subscriptions[name];
	if ( url != null && url.length > 0 ) {
		rmFxCore.statusSet (g_reminderFoxBundle.getString("rf.options.customlist.subscribe.retrieve.title") + " " + url);
		var webcalIndex = url.indexOf( "webcal://");	  // handle webcal address
		if ( webcalIndex != -1 ) {
			url = "http://" + url.substring( "webcal://".length );
		}
		reminderFox_download_Startup_headless_URL(REMINDER_FOX_UI_MODE_HEADLESS_SHOW_ERRORS,reminderFox_downloadSubscribedCalendarCallback, url, subscribedCal, null);
	}
	
}

function reminderFox_downloadSubscribedCalendarCallback( statustxtString, actionID, downloadedReminders ) {
		
		if ( actionID == 1 ) {  // completed successfully (remote and local are equal, or were uploaded)
			rmFxCore.statusSet ("");
		}
		else if ( actionID == 2 ) { // reminders were downloaded,  need to refresh reminders 
			var subscribedCalArr =	getSubscribedCalendars();
			var tabList = document.getElementById("tabList");	
			var tab =	tabList.selectedItem;
			var tabIndex =	tabList.selectedIndex;
			var index = tab.id.indexOf( ':' );		
			name = tab.id.substring( index +1 , tab.id.length );
			
			var subscribedCal = subscribedCalArr[name];
			if ( subscribedCal == null ) {				
				subscribedCal = new Array();
				subscribedCalArr[name] = subscribedCal;
			}
			subscribedCal = downloadedReminders;
				
			selectCalendarSync = false;
		 	// remove all of the calendar items and re-add them
			removeAllListItems( true, false);	  
			calendarReminderArray = null;  // null out in case reminder columns are sorted
			fillList(true, false);	
			selectCalendarSync = true;   
		   
		   oeDatePicker.redrawYear();
		   oeDatePicker.redrawDays();			
			rmFxCore.statusSet ("");
		}
		else {
			rmFxCore.statusSet (statustxtString);
		}
		
}

	

function createTodoListItem(todo, sort, todaysDate, addToArray ) {
	var tree ;
	var treeSelection
	var boxobject;
	var item;	
	if (rmFx_ViewThis(todo, "todos") == 0)  {return};

//gW_Search <<< ------	
		if ( isListFiltered( )) {
			var rmSearchText =lastTodoSearchText.toLowerCase();
			if ( !eventMatchesFilterText( todo, rmSearchText, currentTodoSearchItemValue) ) {
				return; 
			}
			
//			try {		/*  'try'	to skip for invalid 'Item' description */
//				if (todo[searchItems[currentTodoSearchItemValue]].toLowerCase().search(rmSearchText) == -1) {
//					 return;
//				}					 
//			} catch (e)  {return};
		}
// --->>>

	// if this todo is completed and the user wants to hide completed items,
	// don't add it to the list
	if (HIDE_COMPLETED_ITEMS &&
			 todo.completedDate != null ) { 
		return;	
	}

	var treeChildren = document.getElementById("todoTreechildren");
	var newItem = document.createElement("treeitem");
	var newRow = document.createElement("treerow");
	newRow.setAttribute( REMINDER_ID_REF, todo.id );	
	var newDateLabel = document.createElement("treecell");
	var newDescLabel = document.createElement("treecell");
	 		 		newDescLabel.setAttribute("align", "end");
	
	newItem.appendChild(newRow);
	newRow.appendChild(newDateLabel);
	newRow.appendChild(newDescLabel);
	var isImportant = false;
	
	if ( todo.date != null ) {
		var monthAsText = reminderFox_getMonthAsText(todo.date.getMonth());		
		if ( useDefaultDate ) {
			newDateLabel.setAttribute("label", monthAsText + " " + todo.date.getDate());
		}
		else {
			newDateLabel.setAttribute("label", reminderFox_getDateVariableString( todo, todo.date ) );
		}	
		newRow.setAttribute( REMINDER_DATE_REF, todo.date.getTime() );
//		var dayVal = todo.date.getDate();
//		var monthArray = calendarTodoArray[todo.date.getMonth()];
//		if ( monthArray == null ) {
//			monthArray = new Array(31);
//			calendarTodoArray[todo.date.getMonth()] = monthArray;
//		}

//		todo = reminderFox_processReminderDescription(reminder, todaysDate.getFullYear(), false);	
		if ( addToArray ) {
			if ( calendarTodoArray == null ) { 
				//createCalendarTodoArray();				
				calendarTodoArray = new Array(12);  
			}
		
			todo = reminderFox_processReminderDescription(todo, todaysDate.getFullYear(), false);	
		
			var monthArray = calendarTodoArray[todo.date.getMonth()];
			if ( monthArray == null ) {
				monthArray = new Array(31);
				calendarTodoArray[todo.date.getMonth()] = monthArray;
			}
				
			var monthDay = todo.date.getDate();
			var dayReminderArray = monthArray[monthDay - 1];
			if ( dayReminderArray == null ) {
				dayReminderArray = new Array();
				monthArray[monthDay - 1] = dayReminderArray;
			}
			length = dayReminderArray.length;
			
			var ignoreReminder = false;			
			if (HIDE_COMPLETED_ITEMS &&
						 todo.completedDate != null ) { 
					ignoreReminder = true;			
			}
	
			if ( !ignoreReminder ) {
				dayReminderArray[length] = todo;
			}	
		}
			

//	if ( calendarTodoArray == null ) {
//		createCalendarTodoArray();
//	}

//	createCalendarTodoArray();
		
	}

	todo = reminderFox_processReminderDescription(todo,  todaysDate.getFullYear(), true );		
	newDescLabel.setAttribute("label", todo.summary);
	
	var newTimeLabel = document.createElement("treecell");
	newRow.appendChild(newTimeLabel);			
	if ( todo.date != null ) { 
		if ( todo.allDayEvent ) {
			newTimeLabel.setAttribute("label", REMINDER_FOX_TIME_ALL_DAY_LABEL);
		}
		else {
			var time = reminderFox_getAddTimeString(todo);
			if ( time == null ) {
				newTimeLabel.setAttribute("label", REMINDER_FOX_TIME_ALL_DAY_LABEL);
			}
			else {			
				newTimeLabel.setAttribute("label", time);
			}
		}
	}
	
	var newCompletedDateLabel = document.createElement("treecell");
	newRow.appendChild(newCompletedDateLabel);				
			
	
	var newCompletedLabel = document.createElement("treecell");
	newRow.appendChild(newCompletedLabel);

	var newTodoShowInTooltip = document.createElement("treecell");
	newRow.appendChild(newTodoShowInTooltip);
	
	// check for any options that are specified, and mark them in the columns 
	if ( todo.priority == REMINDER_PRIORITY_IMPORTANT) { 
            newDescLabel.setAttribute("properties", "important");
            isImportant = true;
     }
     
     if ( todo.completedDate != null  ) {
     	newCompletedLabel.setAttribute("src",REMINDER_FOX_COMPLETED_TODO_IMAGE);			
    	 if ( isImportant ) {
    	 	newDescLabel.setAttribute("properties", "imporantCompleteText");     	
    	 }
    	 else {
    	 	newDescLabel.setAttribute("properties", "completeText");     	
    	 }
    	 
		if ( useDefaultDate ) {
			var monthAsText = reminderFox_getMonthAsText(todo.completedDate.getMonth());		
			newCompletedDateLabel.setAttribute("label", monthAsText + " " + todo.completedDate.getDate());
		}
		else {
			newCompletedDateLabel.setAttribute("label", reminderFox_getDateVariableString( todo, todo.completedDate ) );
		}    	 
     }
     
     if ( todo.showInTooltip ) {
         	 newTodoShowInTooltip.setAttribute("src", REMINDER_FOX_SHOW_IN_TOOLTIP_IMAGE);		
     }	
     
	var newNotesLabel = document.createElement("treecell");
	newRow.appendChild(newNotesLabel);	
  	if ( todo.notes != null ) {
 		newNotesLabel.setAttribute("src",REMINDER_FOX_NOTES_IMAGE);			
 		//newNotesLabel.setAttribute("properties", "align='center'");
 		// 	newNotesLabel.setAttribute("align", "end");
     	//newNotesLabel.setAttribute("properties", "notes"); 		
 	}     	
 	
	var alarmLabel = document.createElement("treecell");
	newRow.appendChild(alarmLabel);		 	
	
 	if ( todo.alarm != null ) {
		if ( todo.snoozeTime != null && todo.completedDate == null  ) { 
			alarmLabel.setAttribute("src",REMINDER_FOX_ALARM_SNOOZE_IMAGE);		
		}
		else {
 			alarmLabel.setAttribute("src",REMINDER_FOX_ALARM_IMAGE);			
		}
     }       	
     
     
   	var categoriesLabel = document.createElement("treecell");
	newRow.appendChild(categoriesLabel);		
	if ( todo.categories != null ) {
		 categoriesLabel.setAttribute("label", todo.categories);
	}

	var endDateLabel = document.createElement("treecell");
	newRow.appendChild(endDateLabel);		
	
	if ( todo.date != null && todo.endDate != null ) {
		var myEndDate = new Date( todo.date.getTime() + todo.durationTime );
		if ( todo.allDayEvent ) {
			myEndDate.setDate( myEndDate.getDate() -1 ); // all-day offset
		}
		if ( useDefaultDate ) {
			var monthAsText = reminderFox_getMonthAsText(myEndDate.getMonth());		
			endDateLabel.setAttribute("label", monthAsText + " " + myEndDate.getDate());
		}
		else {
			endDateLabel.setAttribute("label", reminderFox_getDateVariableString( todo, myEndDate ) );
		}
	}


	if (reminderFox_isMailEvent(todo) ) {
 		var newMailLabel = document.createElement("treecell");
		newRow.appendChild(newMailLabel);	
 		newMailLabel.setAttribute("src",REMINDER_FOX_MAIL_IMAGE);			
 	} 	
    
	var treeitems = treeChildren.childNodes;
	if( !sort || treeitems.length == 0 ) {
        treeChildren.appendChild(newItem);
        if ( treeitems.length == 1 ) {
            var treeSelection = document.getElementById("todoTree").view.selection;	
			treeSelection.select(0);
        }
	}
    // if current todo is not important, add after important items
    else if ( !isImportant) {
		var added = false;
		for (var i=0; i < treeitems.length && !added; i++) {
			item = treeitems[i];
			var row = item.childNodes[0];
			var todoRefId = row.getAttribute(REMINDER_ID_REF);			
			var todoAtIndex = reminderFox_getTodosById( todoRefId,  getCurrentTodoList() );		

			var descCell = row.childNodes[0];
			var descLabel = descCell.getAttribute("label");		
 			if ( !todoAtIndex.priority == REMINDER_PRIORITY_IMPORTANT ) {
	        	if (  todo.showInTooltip ) {
	     			treeChildren.insertBefore(newItem, item);
					added = true;	        	
					// highlight the newly added reminder in the list
					tree = document.getElementById("todoTree");	
					treeSelection = tree.view.selection;	
					try {
						treeSelection.select(i);
					}
					catch( e ) {
						reminderFox_logMessageLevel( "Error in selectReminderById1: " +
								e.message   , REMINDER_FOX_LOG_LEVEL_INFO);  //TODO
						reminderFox_logMessageLevel( "Error in selectReminderById1: " +
								e.message   , REMINDER_FOX_LOG_LEVEL_DEBUG);  //TODO
					}				
	
					boxobject = tree.boxObject;
					boxobject.ensureRowIsVisible(i);
				}
	        	else {
	        		if ( !todoAtIndex.showInTooltip  ) {
						treeChildren.insertBefore(newItem, item);
						added = true;
						// highlight the newly added reminder in the list
						tree = document.getElementById("todoTree");	
						treeSelection = tree.view.selection;	
						try {
							treeSelection.select(i);
						}
						catch( e ) {
							reminderFox_logMessageLevel( "Error in selectReminderById1: " +
									e.message   , REMINDER_FOX_LOG_LEVEL_INFO);  //TODO
							reminderFox_logMessageLevel( "Error in selectReminderById1: " +
									e.message   , REMINDER_FOX_LOG_LEVEL_DEBUG);  //TODO
						}
						
						boxobject = tree.boxObject;
						boxobject.ensureRowIsVisible(i);
	        		}
	        	}
	        
	        }
		}
	
    	if ( !added ) {
           	treeChildren.appendChild(newItem);
			// highlight the newly added reminder in the list 	 
	    	tree = document.getElementById("todoTree");	
	    	treeSelection = tree.view.selection;	
			treeSelection.select(treeitems.length - 1);			
							
			boxobject = tree.boxObject;
			boxobject.ensureRowIsVisible(treeitems.length - 1);
       }
    }
    // new Todo is important - add to top of list
    else {        		
    	item = treeitems[0];
    	treeChildren.insertBefore(newItem, item);
		added = true;	
		// highlight the newly added reminder in the list
		tree = document.getElementById("todoTree");	
		treeSelection = tree.view.selection;	
		treeSelection.select(0);

		boxobject = tree.boxObject;
		boxobject.ensureRowIsVisible(0);
    }	
          
    
}


function createTodoListItemAtIndex(todo, index) {
	var tree ;
	var treeSelection
	var boxobject;
	var item;	

	var treeChildren = document.getElementById("todoTreechildren");
	var newItem = document.createElement("treeitem");
	var newRow = document.createElement("treerow");
	newRow.setAttribute( REMINDER_ID_REF, todo.id );	
	var newDateLabel = document.createElement("treecell");	
	var newDescLabel = document.createElement("treecell");

	newItem.appendChild(newRow);
	newRow.appendChild(newDateLabel);
	newRow.appendChild(newDescLabel);
	var isImportant = false;
	
	if ( todo.date != null ) {
		var monthAsText = reminderFox_getMonthAsText(todo.date.getMonth());		
		if ( useDefaultDate ) {
			newDateLabel.setAttribute("label", monthAsText + " " + todo.date.getDate());
		}
		else {
			newDateLabel.setAttribute("label", reminderFox_getDateVariableString( todo, todo.date ) );
		}	
		newRow.setAttribute( REMINDER_DATE_REF, todo.date.getTime() );
	}	
	todo = reminderFox_processReminderDescription(todo,  new Date().getFullYear(), true );			
	newDescLabel.setAttribute("label", todo.summary);
	var newTimeLabel = document.createElement("treecell");
	newRow.appendChild(newTimeLabel);			
	if ( todo.date != null ) { 
		if ( todo.allDayEvent ) {
			newTimeLabel.setAttribute("label", REMINDER_FOX_TIME_ALL_DAY_LABEL);
		}
		else {
			var time = reminderFox_getAddTimeString(todo);
			if ( time == null ) {
				newTimeLabel.setAttribute("label", REMINDER_FOX_TIME_ALL_DAY_LABEL);
			}
			else {			
				newTimeLabel.setAttribute("label", time);
			}
		}	
	}
	
	var newCompletedDateLabel = document.createElement("treecell");
	newRow.appendChild(newCompletedDateLabel);				
			

	var newCompletedLabel = document.createElement("treecell");
	newRow.appendChild(newCompletedLabel);
				
	var newTodoShowInTooltip = document.createElement("treecell");
	newRow.appendChild(newTodoShowInTooltip);
	
	// check for any options that are specified, and mark them in the columns 
	if ( todo.priority == REMINDER_PRIORITY_IMPORTANT) { 
            newDescLabel.setAttribute("properties", "important");
            isImportant = true;
     }
     
     if ( todo.completedDate != null  ) {
     	newCompletedLabel.setAttribute("src",REMINDER_FOX_COMPLETED_TODO_IMAGE);	
    	 if ( isImportant ) {
    	 	newDescLabel.setAttribute("properties", "imporantCompleteText");     	
    	 }
    	 else {
    	 	newDescLabel.setAttribute("properties", "completeText");     	
    	 }    
    	  		
		if ( useDefaultDate ) {
			var monthAsText = reminderFox_getMonthAsText(todo.completedDate.getMonth());		
			newCompletedDateLabel.setAttribute("label", monthAsText + " " + todo.completedDate.getDate());
		}
		else {
			newCompletedDateLabel.setAttribute("label", reminderFox_getDateVariableString( todo, todo.completedDate ) );
		}     	 	
     }     
     
     if ( todo.showInTooltip ) {	
         	 newTodoShowInTooltip.setAttribute("src", REMINDER_FOX_SHOW_IN_TOOLTIP_IMAGE);		         
     }	
	
	var newNotesLabel = document.createElement("treecell");
	newRow.appendChild(newNotesLabel);	
  	if ( todo.notes != null ) {
 		newNotesLabel.setAttribute("src",REMINDER_FOX_NOTES_IMAGE);			
 		//newNotesLabel.setAttribute("properties", "align='center'");
 		newNotesLabel.setAttribute("align", "end");
     	//newNotesLabel.setAttribute("properties", "notes"); 			
 	}     	     
	
	var alarmLabel = document.createElement("treecell");
	newRow.appendChild(alarmLabel);		 	
	
 	if ( todo.alarm != null ) {
		if ( todo.snoozeTime != null && todo.completedDate == null ) { 
			alarmLabel.setAttribute("src",REMINDER_FOX_ALARM_SNOOZE_IMAGE);		
		}
		else {
 			alarmLabel.setAttribute("src",REMINDER_FOX_ALARM_IMAGE);			
		}    	    	
     }       	
     
    var categoriesLabel = document.createElement("treecell");
	newRow.appendChild(categoriesLabel);			
	if ( todo.categories != null ) {
		 categoriesLabel.setAttribute("label", todo.categories);
	} 	 	
	
	var endDateLabel = document.createElement("treecell");
	newRow.appendChild(endDateLabel);		
	if ( todo.date != null && todo.endDate != null ) {
		var myEndDate = new Date( todo.date.getTime() + todo.durationTime );
		if ( todo.allDayEvent ) {
			myEndDate.setDate( myEndDate.getDate() -1 ); // all-day offset
		}
		if ( useDefaultDate ) {
			var monthAsText = reminderFox_getMonthAsText(myEndDate.getMonth());		
			endDateLabel.setAttribute("label", monthAsText + " " + myEndDate.getDate());
		}
		else {
			endDateLabel.setAttribute("label", reminderFox_getDateVariableString( todo, myEndDate ) );
		}
	}
 	
	if (reminderFox_isMailEvent(todo) ) {
 		var newMailLabel = document.createElement("treecell");
		newRow.appendChild(newMailLabel);	
 		newMailLabel.setAttribute("src",REMINDER_FOX_MAIL_IMAGE);			
 	} 	 	
    
	var treeitems = treeChildren.childNodes;	
	// insert at end if last item
	if ( index >= treeitems.length ) {
        treeChildren.appendChild(newItem);
        // highlight the newly added reminder in the list 	 
        tree = document.getElementById("todoTree");	
        treeSelection = tree.view.selection;	
        treeSelection.select(treeitems.length -1 );			
                        
        boxobject = tree.boxObject;
        boxobject.ensureRowIsVisible(treeitems.length -1 );	
	
	}
	else {
		// otherwise insert before current item at index
		item = treeitems[index ];
		treeChildren.insertBefore(newItem, item);
		
		tree = document.getElementById("todoTree");	
		treeSelection = tree.view.selection;	
		treeSelection.select(index);					
	
		boxobject = tree.boxObject;
		boxobject.ensureRowIsVisible(index);	
	}
}


/**
  * select (highlight) today's reminder or the next upcoming reminder
  */
function highlightClosestUpcomingReminder(currentDate) {
	var currentMonth = currentDate.getMonth();
	var currentDay = currentDate.getDate();
	var treeChildren = document.getElementById("treechildren");
	var treeitems = treeChildren.childNodes;
	
	// get selected events into visable part of bug
	//    https://www.mozdev.org/bugs/show_bug.cgi?id=21565
    var tree = document.getElementById("reminderTree");           
    var boxobject = tree.boxObject;
    boxobject.QueryInterface(Components.interfaces.nsITreeBoxObject);
    boxobject.scrollToRow(0);

	for (var i=0; i < treeitems.length; i++) {
		var item = treeitems[i];
		var row = item.childNodes[0];
		
		var reminderDateTime = row.getAttribute(REMINDER_DATE_REF);	
		var reminderDate = new Date(parseInt(reminderDateTime));
		if ( reminderDate.getMonth() > currentMonth || (reminderDate.getMonth() == currentMonth && reminderDate.getDate() >= currentDay ) ) {
			var treeSelection = document.getElementById("reminderTree").view.selection;
			if ( treeSelection != null ) {
				try { 
					treeSelection.select(i);
				}
				catch ( e ) {
					// when changing calendar years, selecting an event and syncing to the calendar seemed screwed up
				}
				
			}
			
			// make sure that newly selected row is shown in scroll pane
			var value = document.getElementById("treeparent").value;
		  	var tree = document.getElementById("reminderTree");			
			var boxobject = tree.boxObject;
			boxobject.QueryInterface(Components.interfaces.nsITreeBoxObject);
			
			// make sure it shows up at the top if possible
			var first = boxobject.getFirstVisibleRow();
			var last = boxobject.getLastVisibleRow();
			if ( i < first || i > last ) {				
				boxobject.scrollToRow(treeitems.length - last);
				
			}
			
			var previousReminderOffset = 3;
			if ( i < previousReminderOffset ) { 
				boxobject.ensureRowIsVisible(i);
			}
			else {
				boxobject.ensureRowIsVisible(i  - previousReminderOffset);
			}
//			alert( "first: " + first + " --last: " + last );
//			boxobject.scrollToRow(treeitems.length );
			break;
		}
	}
}

/**
  * select (highlight) today's reminder or the next upcoming reminder
  */
function highlightReminderForDate(currentMonth, currentDay) { 
	var highlighted = false;
	var treeChildren = document.getElementById("treechildren");
	var treeitems = treeChildren.childNodes;
	for (var i=0; i < treeitems.length; i++) {
		var item = treeitems[i];
		var row = item.childNodes[0];
		
		var reminderDateTime = row.getAttribute(REMINDER_DATE_REF);	
		var reminderDate = new Date(parseInt(reminderDateTime));		

		if ( reminderDate.getMonth() == currentMonth && reminderDate.getDate() == currentDay ) {
			highlighted = true;
			var treeSelection = document.getElementById("reminderTree").view.selection		
			if ( treeSelection != null ) {
				try { 
					treeSelection.select(i);
				}
				catch (e) {
					reminderFox_logMessageLevel( "Error in highlightReminderForDate: " +
						e.message   , REMINDER_FOX_LOG_LEVEL_INFO);  //TODO
					rmFxUtil.dump2Console('error', e.message + "; highlightReminderForDate");
				}
			}

			// make sure that newly selected row is shown in scroll pane
			var value = document.getElementById("treeparent").value;
		  	var tree = document.getElementById("reminderTree");			
			var boxobject = tree.boxObject;
			boxobject.QueryInterface(Components.interfaces.nsITreeBoxObject);
			
			// make sure it shows up at the top if possible
			var first = boxobject.getFirstVisibleRow();
			var last = boxobject.getLastVisibleRow();
			
			if ( i <= first || i >= last ) {				
				boxobject.scrollToRow(treeitems.length - 9);
			}
			
			var previousReminderOffset = 3;
			if ( i < previousReminderOffset ) { 
				boxobject.ensureRowIsVisible(i);
			}
			else {
				boxobject.ensureRowIsVisible(i  - previousReminderOffset);
			}
			break;
		}
	}
	
	if ( !highlighted ) {
		selectNewReminderText();
	}
}

function highlightTodo() {
	var tree = document.getElementById("todoTree");			
	var treeSelection = tree.view.selection;	
	treeSelection.select(0);	
	treeSelection.clearSelection();

	try {			
		var boxobject = tree.boxObject;
		boxobject.ensureRowIsVisible(0);
	} catch (ex) {}	
}


function removeListItemsForReminder(reminder) {
	var treeChildren = document.getElementById("treechildren");
	var treeitems = treeChildren.childNodes;
	for (var i=treeitems.length - 1; i >= 0; i--) {
		var item = treeitems[i];
		var row = item.childNodes[0];
		var reminderRefId = row.getAttribute(REMINDER_ID_REF);	
		if ( reminderRefId == reminder.id ) {			
			treeChildren.removeChild(item);
		}
	}
}

/*
 *    @param messageIDtagging  used with 'multiple' deleting messages to
 *           prevent not to open 'all' releated messages and folders
 */
function removeTodoListItem(todo, messageIDtagging ) { 
	var treeChildren = document.getElementById("todoTreechildren");
	var treeitems = treeChildren.childNodes;
	for (var i=0; i < treeitems.length; i++) {
		var item = treeitems[i];
		var row = item.childNodes[0];
		var todoRefId = row.getAttribute(REMINDER_ID_REF);		
		if ( todoRefId == todo.id ) {			
			treeChildren.removeChild(item);
			
			// gW 2008-12-14
			// need to clear Mail label if a message is attached to this reminder
			if (( todo.messageID != null ) && (messageIDtagging)){		
				if ( window.arguments != null ) {				
					var clearMailLabelCallback = window.arguments[1].clearMailLabelCallback;
					if ( clearMailLabelCallback != null ) {				
						clearMailLabelCallback(  todo.messageID );
					}
				}
			}	
			
			break;
		}
	}	
}


// saves and closes the 'edit reminders' dialog
function revert() {
	// there were changes.  Prompt user to revert/cancel
	// get a reference to the prompt service component.
	var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
	                    .getService(Components.interfaces.nsIPromptService);

	var flags=promptService.BUTTON_TITLE_IS_STRING * promptService.BUTTON_POS_0 +
   	promptService.BUTTON_TITLE_IS_STRING * promptService.BUTTON_POS_1;     
	var msg =  g_reminderFoxBundle.getString("rf.add.revert.description");
	var buttonPressed = promptService.confirmEx(window,g_reminderFoxBundle.getString("rf.add.revert.title"),
	  msg,
	  flags, g_reminderFoxBundle.getString("rf.add.revert.button.revert.title"), g_reminderFoxBundle.getString("rf.button.cancel"), null, null, {});		  
	  
	// revert pressed
	if ( buttonPressed == 0 ) {		
		revertActions();
	}	
}

function removeAllListItems(removeReminders, removeTodos) {
	if ( removeReminders ) {
		var reminderTree = document.getElementById("reminderTree");
		var treeChildren = document.getElementById("treechildren");
		reminderTree.removeChild(treeChildren);
		
		var newchildren = document.createElement("treechildren");
		newchildren.setAttribute("id", "treechildren");
		newchildren.setAttribute("ondblclick", "if (event.button == 0) editReminder()");
		newchildren.setAttribute("onclick", "reminderFox_toggleReminderColumns(event);");		
		
		newchildren.setAttribute("tooltip", "reminderTree-tooltip");
		reminderTree.appendChild(newchildren);
	}

	if ( removeTodos ) {
		var todoTreeChildren = document.getElementById("todoTreechildren");
	     while (todoTreeChildren.hasChildNodes()) {	
	    	 todoTreeChildren.removeChild(todoTreeChildren.firstChild);
	  	 }		
	 }	
}


// saves and closes the 'edit reminders' dialog
function saveSettings(isCloseDemanded) {
	var currentDate = new Date();
	var day = currentDate.getDate();
	var windowEnumerator = reminderFox_getWindowEnumerator();
	var currentWindow;
	var daysChanged = false;


	// see if the day has changed since last process
	if (windowEnumerator.hasMoreElements()) {
		currentWindow = windowEnumerator.getNext();		
		if ( currentWindow.reminderFox_lastDay != day ) {
			daysChanged = true;
		}
	}
	
	// write out column sort info
	var listSortStr = "";
	for ( var n in listSortMap ) {
		var sortInfo = listSortMap[n];
		if ( sortInfo != null ) {
			if ( listSortStr != "" ) {
				listSortStr = listSortStr + ",";
			}
			listSortStr = listSortStr + n + "," + sortInfo.sortColumn + "," + sortInfo.sortDirection;;
		}
	}
	reminderFox_setUnicodePref( REMINDER_FOX_SORT_COLUMNS_PREF, listSortStr);		
	

	
	reminderFox_setPreferenceValue( REMINDER_FOX_SHOW_FILTERS, showFilters);	
	reminderFox_setPreferenceValue( REMINDER_FOX_SHOW_SIDEBAR, showSidebar);	
	reminderFox_logMessageLevel("Saving...  g_modified: " + g_modified + " _daysChanged: " +daysChanged , REMINDER_FOX_LOG_LEVEL_DEBUG);
	// if any events were modified or the day has changed, we want to update the tooltip and status text
	if ( g_modified || daysChanged ) {  
		reminderFox_writeOutRemindersAndTodos(false);
		
		reminderFox_processRecentReminders(true);
		try {
			// update all of the browsers
			windowEnumerator =  reminderFox_getWindowEnumerator();
			while (windowEnumerator.hasMoreElements()) {
				var currentWindow = windowEnumerator.getNext();		
				currentWindow.reminderFoxEvents = reminderFoxEvents;
				currentWindow.reminderFoxTodosArray  = reminderFoxTodosArray; 

				currentWindow.reminderFox_updateRemindersInWindow();			
				currentWindow.reminderFox_clearRemindersAndTodos();
			}			
			// this callback syncs the written changes to remote and does it in the background on the calling 
			// window (otherwise we have to keep this window open until the network function callback returns)
			var syncCallback = null;
			if ( window.arguments != null ) {
				syncCallback = window.arguments[1].callback;
			}
			if ( syncCallback != null ) {				
				var networkSync = REMINDER_FOX_NETWORK_SYNCHRONIZE_DEFAULT;		
				try {
					networkSync = reminderFox_prefs.getBoolPref(REMINDER_FOX_PREF + "." + REMINDER_FOX_NETWORK_SYNCHRONIZE);
				} catch(e) {
				}	
				if ( networkSync ) {				
					syncCallback();			
				}
			}	
		}
		catch(e) {
		}
	}
	else {
		 reminderFox_ensureRemindersSynchronized(); 		
		
		// call reminderFox_intializeReminderFox to check in case the timers have stopped; this will restart 
		// it and process any reminders if necessary (such as alarms, etc)
		var processRemindersCallback = null;
		if ( window.arguments != null ) {
			processRemindersCallback = window.arguments[1].processRemindersCallback;
		}
		if ( processRemindersCallback != null ) {	
			processRemindersCallback(true);		
		}	
	}

	// clear reminders from memory
	reminderFox_clearRemindersAndTodos();
	g_modified = false;
}

function addReminderOrTodo() {
	if ( isReminderTabSelected() ) {
		addReminder(); 
	}
	else {
		addTodo();
	}
}

function dblClickDay(newDayItemNumber) {
   var dayNumberItem = document.getElementById( "oe-date-picker-month-day-text-" + newDayItemNumber );
   var dayNumber = dayNumberItem.getAttribute( "value" );
   
   // they may have clicked an unfilled day, if so ignore it and leave the picker up   
   if( dayNumber != "" )  {
   		if ( isReminderTabSelected() ) {
			addReminder(); 
		}
		else {
			var newDate = oeDatePicker.gSelectedDate;
			if ( newDate == null ) {
				newDate = new Date();
			}	
			addTodo(newDate);
		}
   }
}

// Adds the new reminder from the edit reminder dialog
function addReminder( useTodaysDate, newReminderToBeAdded) {
	var newDate = oeDatePicker.gSelectedDate;
	var todaysDate = new Date();
	if ( newDate == null ) {
		newDate = new Date();
	}	
	
	var originalYear = newDate.getFullYear();
	
	if ( useTodaysDate ) {
		// use today's date (but the selected year...)
		newDate = new Date( originalYear, todaysDate.getMonth(), todaysDate.getDate());
	}
	
	
	var copyingReminder = false;
	if ( newReminderToBeAdded == null ) {
		var reminderId =reminderFox_generateUniqueReminderId( newDate );
		newReminderToBeAdded = new ReminderFoxEvent( reminderId, newDate, "" );
	}
	else {
		copyingReminder = true;
	}
	
	var newOptions = { reminder: newReminderToBeAdded, editing:  copyingReminder,  copying: copyingReminder, addReminder: false, readonly: isSubscribedCalendarTabSelected() };
	window.openDialog("chrome://reminderfox/content/editing/reminderOptionsDialog.xul",
			"reminderOptionsDialog", "chrome,resizable,modal", newOptions );

	if ( newOptions.addReminder ) {
		reminderFox_logMessageLevel("New reminder: "+ newOptions.reminder.summary  + " " +  newOptions.reminder.date, REMINDER_FOX_LOG_LEVEL_DEBUG);
		var currentDate = new Date();
		if ( newReminderToBeAdded.alarm != null ) {
			newReminderToBeAdded.alarmLastAcknowledge = currentDate.getTime();
		}
		newReminderToBeAdded.lastModified = reminderFox_getDateAsString(currentDate );

		// if adding a new reminder in a different year, first set the list/calendar to the new year 
		// before adding the reminder
		if ( originalYear != newReminderToBeAdded.date.getFullYear() ) {
		   	oeDatePicker.gSelectedDate = newReminderToBeAdded.date;
			repopulateListForYear( originalYear, newReminderToBeAdded.date.getFullYear() );
		}
	
		// add reminder in sorted order...
		var reminders = reminderFox_getReminderEvents();	
		var sortedIndex = reminderFox_getSortedIndexOfNewReminder( reminders, newReminderToBeAdded, false );
		reminderFox_insertIntoArray( reminders, newReminderToBeAdded, sortedIndex );
		reminderFox_logMessageLevel("Adding: creating list item" , REMINDER_FOX_LOG_LEVEL_DEBUG);
		createListItem(newReminderToBeAdded);
		reminderFox_logMessageLevel("Adding: sorting" , REMINDER_FOX_LOG_LEVEL_DEBUG);
		
		sortReminderIfNeccessary( newReminderToBeAdded.id);
		reminderFox_logMessageLevel("Adding: completed sort" , REMINDER_FOX_LOG_LEVEL_DEBUG);
		oeDatePicker.onpopupshowing(newReminderToBeAdded.date);
		modifiedReminders();
	}
}

function modifiedReminders() {
	
	g_modified = true;

	var revertButton= document.getElementById("revertbutton");
	// revertButton.setAttribute( "disabled", false );
	revertButton.removeAttribute("disabled");
	var revertButtonTodos= document.getElementById("revertbuttonTodos");
	// revertButtonTodos.setAttribute( "disabled", false );
	revertButtonTodos.removeAttribute("disabled");
}

function addTodo(selectedDate, newTodo) {
	var tabList = document.getElementById("tabList");	
	var tabIndex =	tabList.selectedIndex;

	var copyingTodo = false;
	if ( newTodo == null ) {
		var todoId =reminderFox_generateUniqueTodoId(selectedDate);
		newTodo = new ReminderFoxTodo(todoId, "" );
		newTodo.date = selectedDate;
		if ( tabIndex <= 1 ) {
			var showInTooltipDefault =  reminderFox_getPreferenceValue( REMINDER_FOX_DEFAULT_SHOW_IN_TOOLTIP );	
			if ( showInTooltipDefault || newTodo.showInTooltip == true  ) {
					newTodo.showInTooltip = true;
			}
			else {
					newTodo.showInTooltip = false;
			}
		}
		else {
			newTodo.showInTooltip = false;   // for custom lists, default to false for show in tooltip
		}
	}
	else {
		copyingTodo = true;
	}
	


	var newOptions = { todo: newTodo, editing:  copyingTodo, copying:  copyingTodo,  addTodo: false };
	window.openDialog("chrome://reminderfox/content/editing/todoOptionsDialog.xul",
			"todoOptionsDialog", "chrome,resizable,modal", newOptions );

	if ( newOptions.addTodo ) {
		if ( newTodo.alarm != null ) {
			var currentDate = new Date();
			newTodo.alarmLastAcknowledge = currentDate.getTime();
		}
		// add todo in sorted order...
		var todos = getCurrentTodoList();
		var sortedIndex = reminderFox_getSortedIndexOfNewTodo(todos,  newTodo );
		reminderFox_insertIntoArray( todos, newTodo, sortedIndex );
		createTodoListItem(newTodo, true, new Date(), true);
		
		sortTodoIfNeccessary( newTodo.id);
		if ( newTodo.date != null ) {
			oeDatePicker.onpopupshowing(newTodo.date);
		}
		modifiedReminders();
		
		var desc = document.getElementById("addTodoButton");
    	desc.focus();	  
	}
	
}





function editTodo() {
	var currentTodo = getTodoForSelectedItem( );
	if ( currentTodo != null ) {
		var newOptions = { todo: currentTodo, editing:  true,  addTodo: false, showMail: false };
		window.openDialog("chrome://reminderfox/content/editing/todoOptionsDialog.xul",
				"todoOptionsDialog", "chrome,resizable,modal", newOptions );
	
		if ( newOptions.showMail ) {		 	
			reminderFox_displayMailbyMsgID(currentTodo);	
			editTodo();
			return;
		}
	
		if ( newOptions.addTodo ) {		 	
	 		currentTodo = reminderFox_processReminderDescription(currentTodo,  new Date().getFullYear(), true );	
			var modified = updateTodoInList( currentTodo );
			
			sortTodoIfNeccessary( currentTodo.id);
			
			modifiedReminders();
			var newDate = new Date();
			if ( currentTodo.alarm != null ) {
				currentTodo.alarmLastAcknowledge = newDate.getTime();
			}		
			refreshCalendar(true, false);			
		}
	}
}

function getInstanceDateOfLastSelected( currentReminder ) {
	var reminderID = currentReminder.id;
	var treeChildren = document.getElementById("treechildren");
	var selectedIDsHash = {};
	
	var start = new Object();
	var end = new Object();
	var numRanges =  document.getElementById("reminderTree").view.selection.getRangeCount();
	for (var t = numRanges - 1; t >=0;  t-- ) {
	  document.getElementById("reminderTree").view.selection.getRangeAt(t,start,end);
	  for (var v = end.value; v >= start.value; v--){
		    var selectedTreeItem = treeChildren.childNodes[v];
		    var reminderRefId = selectedTreeItem.childNodes[0].getAttribute(REMINDER_ID_REF);
		    if ( reminderRefId == currentReminder.id ) { 
		    	var year = oeDatePicker.gSelectedDate.getFullYear();
				if ( year == null ) {
					year = new Date().getFullYear();
				}		
				
				var reminderDateTime = selectedTreeItem.childNodes[0].getAttribute(REMINDER_DATE_REF);	
				var reminderInstanceDate = new Date(parseInt(reminderDateTime));		
				
				return reminderInstanceDate;
		    }
	  	}
	}
	return null;	
}

/**
 *    Removes Reminders from List
 *    @param currentReminder
 *    @param promptForRecurringDelete
 *    @param deleteDate
 *    @param dateLabel
 *    @param messageIDtagging  used with 'multiple' deleting messages to
 *           prevent not to open 'all' releated messages and folders
 */

function removeReminder( currentReminder, promptForRecurringDelete, deleteDate, dateLabel, messageIDtagging ) {	
	if ( promptForRecurringDelete != null && promptForRecurringDelete == true) {		
		var messageID = currentReminder.messageID;
		
		if ( currentReminder.recurrence.type == REMINDER_RECURRENCE_MONTHLY_DATE ||
			  currentReminder.recurrence.type == REMINDER_RECURRENCE_MONTHLY_DAY ||
			  currentReminder.recurrence.type == REMINDER_RECURRENCE_WEEKLY ||
			  currentReminder.recurrence.type == REMINDER_RECURRENCE_DAILY ) {
			
			// prompt user... 
			var deleteRecurrenceOnly = true;
			
			if ( deleteDate == null ) {
				deleteDate = getInstanceDateOfLastSelected( currentReminder ); 
			}
			if ( dateLabel == null ) {
				dateLabel = reminderFox_getDateVariableString( currentReminder, deleteDate );
			}
									
			var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
	                    .getService(Components.interfaces.nsIPromptService);
	        var deleteDescription =  g_reminderFoxBundle.getString("rf.add.deleteReminderInstance.description") + "\n";
			deleteDescription += dateLabel + ": " + currentReminder.summary + "\n";
			var flags=promptService.BUTTON_TITLE_IS_STRING * promptService.BUTTON_POS_0 +
		  	 	promptService.BUTTON_TITLE_IS_STRING * promptService.BUTTON_POS_1 + 
		   		promptService.BUTTON_TITLE_IS_STRING * promptService.BUTTON_POS_2;
			var msg = deleteDescription; 
			var buttonPressed = promptService.confirmEx(window, g_reminderFoxBundle.getString("rf.add.deleteReminder.title"),  
			  msg,
			  flags,
			  g_reminderFoxBundle.getString("rf.add.deleteReminderInstance.all.button"), 
			  g_reminderFoxBundle.getString("rf.button.cancel"), 
			  g_reminderFoxBundle.getString("rf.add.deleteReminderInstance.currentInstance.button"), 
			  null, {});		  			  
		
			// cancel pressed
			if (  buttonPressed == 1 ) {
				return ;
			}			
			
			// curent instances pressed
			if ( buttonPressed == 2 ) {	
				if ( deleteDate != null ) {
					deleteDate.setDate( deleteDate.getDate() + 1 );
					var instanceReminder = reminderFox_getFirstReminderOccurrenceAfterStartDate( currentReminder, deleteDate );
					var newReminderDate = instanceReminder.date;
					
					var newReminder = reminderFox_cloneReminderFoxEvent(currentReminder);
					newReminder.date = newReminderDate;					
					newReminder.endDate = new Date(parseInt(newReminder.date.getTime()) + newReminder.durationTime);	
					// if the date has changed, treat as a new reminder.  This is because 
					// We want to re-add in the proper sorted order into the list of reminders
					
					removeListItemsForReminder(currentReminder); 
					// remove from model list
					var reminders = reminderFox_getReminderEvents();	
					for( var i = 0; i < reminders.length; i++) {
						if ( reminders[i].id == currentReminder.id ) {
							reminderFox_removeElement(reminders, i);
							break;
						}
					}
					
					// add reminder in sorted order...
					reminders = reminderFox_getReminderEvents();					
					if ( newReminder.remindUntilCompleted != REMINDERFOX_REMIND_UNTIL_COMPLETE_NONE ) {
		     			newReminder.remindUntilCompleted = REMINDERFOX_REMIND_UNTIL_COMPLETE_TO_BE_MARKED;
		     		}				
					var sortedIndex = reminderFox_getSortedIndexOfNewReminder( reminders, newReminder, false );
					reminderFox_insertIntoArray( reminders, newReminder, sortedIndex );
					createListItem(newReminder);				
					return;					
				}
		 	}
		 	else {		 			 		
		 		// delete all instances pressed  - do nothing here; we'll delete as normal
		 	}	 											
		}
			
		// need to clear Mail label (if remove was called from the user AND flagged)
		if (( messageID != null ) && (messageIDtagging))  {		
			if ( window.arguments != null ) {
				var clearMailLabelCallback = window.arguments[1].clearMailLabelCallback;
				if ( clearMailLabelCallback != null ) {				
					clearMailLabelCallback( messageID );
				}
			}
		}	
	}
	
	
	// remove from UI list
	removeListItemsForReminder(currentReminder);
	
	// remove from model list
	var reminders = reminderFox_getReminderEvents();	
	for( var i = 0; i < reminders.length; i++) {
		if ( reminders[i].id == currentReminder.id ) {
			reminderFox_removeElement(reminders, i);
			break;
		}
	}
}


function removeTodo(currentTodo, messageIDtagging) {
	if ( currentTodo != null ) {
		// remove from UI list
		removeTodoListItem(currentTodo, messageIDtagging);
		
		// remove from model list
		var todos = getCurrentTodoList();
		for( var i = 0; i < todos.length; i++) {
			if ( todos[i].id == currentTodo.id ) {
				reminderFox_removeElement(todos, i);
				break;
			}
		}
	}

}

function activateCalendarContext(event, newDayItemNumber) {
	if ( !isReminderTabSelected() ) {
		return; 
	}
	
   var dayNumberItem = document.getElementById( "oe-date-picker-month-day-text-" + newDayItemNumber );
   var dayNumber = dayNumberItem.getAttribute( "value" );
   
   // they may have clicked an unfilled day, if so ignore it and leave the picker up   
   if( dayNumber != "" )  {
		var tree = document.getElementById("reminderTree");
		var treeContextMenu = document.getElementById("treechildren-calendar-contextmenu");
	
		var noExistingReminder = false;
	
		// modify context menu depending on Important reminder status
		var selectedTreeItemIndex = document.getElementById("reminderTree").currentIndex;
		if ( selectedTreeItemIndex == -1 ) {
			noExistingReminder = true;
		}
		var currentReminder = getReminderForSelectedItem( );
		if ( currentReminder == null ) {
			noExistingReminder = true;
		}
		else if ( currentReminder.completedDate != null ) {
			var calendarDate = new Date(oeDatePicker.gSelectedDate.getFullYear(),oeDatePicker.gSelectedDate.getMonth(), dayNumber );			
			if ( reminderFox_compareDates(calendarDate, currentReminder.completedDate ) != 1 ) {			
				noExistingReminder = true;
			}			
		}
		
		// check that it's pointing to the current date; otherwise it means there is no current reminder for this date
		if ( !noExistingReminder ) {
			// check the date from the tree list, as the actual reminder could have an earlier date (if it's
			// set for RemindUntilComplete, for example)
			var treeChildren = document.getElementById("treechildren");
			var selectedTreeItem = treeChildren.childNodes[selectedTreeItemIndex];
			var reminderDateTime = selectedTreeItem.childNodes[0].getAttribute(REMINDER_DATE_REF);	
			var reminderInstanceDate = new Date(parseInt(reminderDateTime));			
			var day = reminderInstanceDate.getDate();
			
			if ( day != dayNumber ) {
				noExistingReminder = true;
			}
		}
		
		var contextMenuImportant = document.getElementById("treechildren-calendar-contextmenu-important");	
		var contextMenuRemindComplete = document.getElementById("treechildren-calendar-contextmenu-remindUntilComplete");			
		var contextMenuComplete = document.getElementById("treechildren-calendar-contextmenu-markAsComplete");	
		var contextEdit = document.getElementById("treechildren-calendar-contextmenu-edit");			
		var contextDelete= document.getElementById("treechildren-calendar-contextmenu-delete");			
		//var contextMoveToTodos = document.getElementById("treechildren-calendar-contextmenu-moveToTodos");		
		if ( noExistingReminder ) {
			contextEdit.setAttribute( "disabled", true );
			contextDelete.setAttribute( "disabled", true );			
		    //contextMoveToTodos.setAttribute( "disabled", true );						
			contextMenuImportant.setAttribute( "disabled", true );
			contextMenuRemindComplete.setAttribute( "disabled", true );
			contextMenuComplete.setAttribute( "disabled", true );			

			contextMenuImportant.setAttribute("checked", "false");	
			contextMenuRemindComplete.setAttribute("checked", "false");	 
			contextMenuComplete.setAttribute("checked", "false");					
		}		
		else {
			contextEdit.removeAttribute( "disabled" );
			contextDelete.removeAttribute( "disabled" );
			//contextMoveToTodos.removeAttribute( "disabled" );
			contextMenuImportant.removeAttribute( "disabled" );
			contextMenuRemindComplete.removeAttribute( "disabled" );
			contextMenuComplete.removeAttribute( "disabled" );
					
			if ( currentReminder.priority != REMINDER_PRIORITY_IMPORTANT ) {
				contextMenuImportant.setAttribute("checked", "false");	
			}
			else {
				contextMenuImportant.setAttribute("checked", "true");	
			}
			
			if ( currentReminder.remindUntilCompleted != REMINDERFOX_REMIND_UNTIL_COMPLETE_NONE) {
				contextMenuRemindComplete.setAttribute("checked", "true");	 
			}
			else {
				contextMenuRemindComplete.setAttribute("checked", "false");	 
			}
			
			
			if ( currentReminder.completedDate == null ) {
					contextMenuComplete.setAttribute("checked", "false");	
			}
			else {
				var treeChildren = document.getElementById("treechildren");
				var selectedTreeItem = treeChildren.childNodes[selectedTreeItemIndex];
				var reminderDateTime = selectedTreeItem.childNodes[0].getAttribute(REMINDER_DATE_REF);	
				var reminderInstanceDate = new Date(parseInt(reminderDateTime));		
				
				if ( reminderFox_isCompletedForDate( currentReminder, reminderInstanceDate ) )  {
						contextMenuComplete.setAttribute("checked", "true");	
				}
				else {
					contextMenuComplete.setAttribute("checked", "false");	
				}
			}
		}
   }
}

function advanceTab() {
	var tabList = document.getElementById("tabList");		
	var tabIndex =	tabList.selectedIndex;
	var tabbox = document.getElementById("tabbox");
	if ( tabIndex == tabList.childNodes.length - 1 ) {
		var newTab = tabList.childNodes[0];
		tabbox.selectedTab = newTab;		
	} 
	else {
		var newTab = tabList.childNodes[tabIndex+1];
		tabbox.selectedTab = newTab;		
	}
}


function activateContext(event) {
	var tree = document.getElementById("reminderTree");
	var contextMenu = document.getElementById("treechildren-contextmenu");	
	
	// modify context menu depending on Important reminder status
	var selectedTreeItemIndex = document.getElementById("reminderTree").currentIndex;
	var currentReminder = getReminderForSelectedItem( );
	if ( selectedTreeItemIndex == -1 || currentReminder == null  ) {
		for ( var i = 0; i < contextMenu.childNodes.length; i++ ) {
			contextMenu.childNodes[i].setAttribute( "disabled", true );
		}
		return;
	}
	else {
		// enable all child menu items
		for ( var i = 0; i < contextMenu.childNodes.length; i++ ) {
			contextMenu.childNodes[i].removeAttribute( "disabled" );
		}		
	}
	var multipleRemindersSelected = false;
	var selectedReminders = getAllSelectedReminders();
	if ( selectedReminders.length > 1 ) { 
		multipleRemindersSelected = true;
	}
	
	var treechildrenContextmenuEdit = document.getElementById("treechildren-contextmenu-edit");	
	if ( multipleRemindersSelected ) { 
		// if multiple reminders selected, disable Edit
		treechildrenContextmenuEdit.setAttribute( "disabled", true );
	}
	else {
		treechildrenContextmenuEdit.removeAttribute( "disabled" );
	}	
	
	// show current lists...
	var moveToList = document.getElementById("treechildren-contextmenu-moveReminderToList-popup");	
	while (moveToList.hasChildNodes()) {
		 moveToList.removeChild(moveToList.firstChild);
	}
	var tabList = document.getElementById("tabList");	
	var tab =	tabList.selectedItem;
	var tabIndex =	tabList.selectedIndex;
	var subscriptions = reminderFox_getSubscriptions();
	var i = 1;
	if ( isSubscribedCalendarTabSelected() ) {
		i = 0;  // allow reminder tab
	}
	for ( ; i < tabList.childNodes.length; i++ ) {  // i =1, because we want to skip reminders
		var tablistItem = tabList.childNodes[i];	
		var tabLabel = tablistItem.getAttribute("label");
		if ( subscriptions[tabLabel] == null ) {  // ignore subscribed calendars
			var menuItem = document.createElement("menuitem");
			menuItem.setAttribute( "label", tabLabel );
			menuItem.setAttribute( "oncommand", "userMoveReminderToTodo(event.target)");
			moveToList.appendChild(menuItem);
		}
	}	
	
	var contextMenuImportant = document.getElementById("treechildren-contextmenu-important");	
	if ( currentReminder.priority != REMINDER_PRIORITY_IMPORTANT ) {
		contextMenuImportant.setAttribute("checked", "false");	
	}
	else {
		contextMenuImportant.setAttribute("checked", "true");	
	}
	
	var contextMenuRemindComplete = document.getElementById("treechildren-contextmenu-remindUntilComplete");	
	if ( currentReminder.remindUntilCompleted != REMINDERFOX_REMIND_UNTIL_COMPLETE_NONE) {
		contextMenuRemindComplete.setAttribute("checked", "true");	 
	}
	else {
		contextMenuRemindComplete.setAttribute("checked", "false");	 
	}

	var contextMenuComplete = document.getElementById("treechildren-contextmenu-markAsComplete");	
	if ( currentReminder.completedDate == null ) {
			contextMenuComplete.setAttribute("checked", "false");	
	}
	else {
		var treeChildren = document.getElementById("treechildren");
		var selectedTreeItem = treeChildren.childNodes[selectedTreeItemIndex];
		var reminderDateTime = selectedTreeItem.childNodes[0].getAttribute(REMINDER_DATE_REF);	
		var reminderInstanceDate = new Date(parseInt(reminderDateTime));		

		if ( reminderFox_isCompletedForDate( currentReminder, reminderInstanceDate ) )  {
				contextMenuComplete.setAttribute("checked", "true");	
		}
		else {
			contextMenuComplete.setAttribute("checked", "false");	
		}
	}
		
	// If reminder is associated with an email, show the View Mail context menu item.  Otherwise, do not.
    var showMail = document.getElementById("treechildren-contextmenu-showMail");	
    if ( showMail != null ) {
		if (!reminderFox_isMailEvent(currentReminder) ) {
			showMail.setAttribute("hidden", "true");	
		}
		else {
			showMail.setAttribute("hidden", "false");	
		}
	}
	
	if ( isSubscribedCalendarTabSelected() ) {  // disable some menu items for subscribed (read-only) calendars
		document.getElementById("treechildren-contextmenu-important").setAttribute( "disabled", true );
		document.getElementById("treechildren-contextmenu-markAsComplete").setAttribute( "disabled", true );
		document.getElementById("treechildren-contextmenu-remindUntilComplete").setAttribute( "disabled", true );
		document.getElementById("treechildren-contextmenu-delete").setAttribute( "disabled", true );
	}
	else {
		document.getElementById("treechildren-contextmenu-important").removeAttribute( "disabled" );
		document.getElementById("treechildren-contextmenu-markAsComplete").removeAttribute( "disabled" );
		document.getElementById("treechildren-contextmenu-remindUntilComplete").removeAttribute( "disabled" );
		document.getElementById("treechildren-contextmenu-delete").removeAttribute( "disabled" );
	}
	
	if (getAllSelectedReminders().length == 0) {
		document.getElementById("treechildren-contextmenu-sendReminder").setAttribute("disabled", "true");
	}	

}

function reminderFox_toggleReminderColumns(event){
	  var row = {}, column = {}, part = {};
	  var tree = document.getElementById("reminderTree");
	  var boxobject = tree.boxObject;
	  boxobject.QueryInterface(Components.interfaces.nsITreeBoxObject);
	  boxobject.getCellAt(event.clientX, event.clientY, row, column, part);

	var rowIndex = row.value;
	if ( rowIndex != -1 && event.button != 2 ) {  // don't handle event if right-clicking (only show context menu)
		var  treeSelection = document.getElementById("reminderTree").view.selection;
				
		if (typeof column.value != "string") {
			if ( column.value != null ) {
	  			column.value = column.value.id;
			}
	 	 }

		// cycler columns do not get selected automatically like other columns.  Must manually 
		// call select
		if ( column.value == "remindUntilCompletedColLabel" ) {
			treeSelection.select(rowIndex);
			toggleRemindUntilCompleted();
		}
		else if ( column.value == "CompleteColLabel" ) {
			treeSelection.select(rowIndex);
			toggleMarkAsComplete();
		}
		else if ( column.value == "mailColLabel" ) {
			treeSelection.select(rowIndex);
			reminderFox_doShowMail();
		}	
		else if ( column.value == "notesColLabel" ||
			column.value == "alarmColLabel" ) {
			treeSelection.select(rowIndex);  
		}			
		
	}
}

function reminderFox_toggleTodoColumns(event){
	  var row = {}, column = {}, part = {};
	  var tree = document.getElementById("todoTree");
	  var boxobject = tree.boxObject;
	  boxobject.QueryInterface(Components.interfaces.nsITreeBoxObject);
	  boxobject.getCellAt(event.clientX, event.clientY, row, column, part);

	var rowIndex = row.value;
	if ( rowIndex != -1 && event.button != 2 ) {  // don't handle event if right-clicking (only show context menu)
		var  treeSelection = document.getElementById("todoTree").view.selection;		
		
	    if (typeof column.value != "string") {
		 	column.value = column.value.id;
		}
	
		if ( column.value == "todoShowInTooltip" ) {
			treeSelection.select(rowIndex);
			toggleTodoShowInTooltip();
		}
		else if ( column.value == "todoCompleteColLabel" ) {
			treeSelection.select(rowIndex);
			toggleTodoMarkAsComplete();
		}
		else if ( column.value == "todoMailColLabel" ) {
			treeSelection.select(rowIndex);
			reminderFox_doShowMailTodo();
		}				
		else if ( column.value == "todoNotesColLabel" ||
			column.value == "todoAlarmColLabel" ) {
			treeSelection.select(rowIndex);  
		}			
	}
}

function getLabelForColumn( columnId ) {
	var column = document.getElementById(columnId);
	return  column.getAttribute("label");
}

function addTooltipWithLabel( tooltipItem, columnId, value, importantStatus, completedStatus, labelText) {
	var hbox = document.createElement("hbox");		
	var columnLabel;	
	if ( columnId == null ) {
		columnLabel = labelText;
	}
	else {
		columnLabel = getLabelForColumn(columnId);		
	}
	
	var title = document.createElement("description");
	title.setAttribute("value",columnLabel + ": ");
	title.setAttribute( "style", "font-weight:bold");
	hbox.appendChild( title );
	
	var tooltipValue = document.createElement("description");
	tooltipValue.setAttribute("value", value );
	
	if ( importantStatus && completedStatus ) {
		tooltipValue.setAttribute( "style", " text-decoration: line-through; color: red" );
	}
	else if ( importantStatus ) {
		tooltipValue.setAttribute( "style", "color: red" );
	}
	else if ( completedStatus ) {
		tooltipValue.setAttribute( "style", " text-decoration: line-through" );
	}
	
	hbox.appendChild( tooltipValue );
	
	tooltipItem.appendChild(hbox);		
}


function reminderTreeTooltip(event) {
 	var tree = document.getElementById("reminderTree");
 	var boxobject = tree.boxObject;
  	boxobject.QueryInterface(Components.interfaces.nsITreeBoxObject);  // cast to treeboxobject to use getRowAt
  
  	var row = {}, column = {}, part = {};
	boxobject.getCellAt(event.clientX, event.clientY, row, column, part);
   	
	if (column.value != null && typeof column.value != "string") {
	 	column.value = column.value.id;
	 }

    
 	var index = tree.boxObject.getRowAt( event.clientX, event.clientY );
 	if ( index == -1 ) {
 		return false;  // returning false causes tooltip to not show
 	} 	
 	var treeChildren = document.getElementById("treechildren");
 	var selectedTreeItem = treeChildren.childNodes[index];
	var reminderRefId = selectedTreeItem.childNodes[0].getAttribute(REMINDER_ID_REF);
	
	var reminder =  reminderFox_getRemindersById( reminderRefId, getCurrentReminderList() );
 	if ( reminder == null ) {
 		return false; // returning false causes tooltip to not show
 	}

 	var tooltipItem = document.getElementById("reminderTree-tooltip-box"); 
     while (tooltipItem.hasChildNodes()) {
    	 	tooltipItem.removeChild(tooltipItem.firstChild);
  	 } 	
  	 
  	 // if this is the alarm column, show the alarm value
	if ( reminder.alarm != null && column.value == "alarmColLabel" ) { 
		// if the alarm is currently snoozed, show the snooze value as well....	
		if ( reminder.snoozeTime != null ) { 
			var snoozeAlarmTime = reminder.snoozeTime;
			var index = snoozeAlarmTime.indexOf( ';' );
			if ( index != -1 ) {
				snoozeAlarmTime = snoozeAlarmTime.substring( 0, index );				
			}		
			var snoozedate = new Date( parseInt(snoozeAlarmTime));	
			var dateString = reminderFox_getDateVariableString( reminder, snoozedate);
			var timeString = reminderFox_mail_getTimeString(snoozedate);
					
			var snoozetitle = document.createElement("description");
			snoozetitle.setAttribute("value",  g_reminderFoxBundle.getString("rf.alarm.list.tooltip.snooze")  + " " + dateString + ", " + timeString);  
			tooltipItem.appendChild(snoozetitle);	
		}
		else {  
			// otherwise show when the next alarm is scheduled for...
			var reminderDateTime = selectedTreeItem.childNodes[0].getAttribute(REMINDER_DATE_REF);	
			var reminderInstanceDate = new Date(parseInt(reminderDateTime));		
			
			var newDate = new Date( reminder.date.getFullYear(), reminder.date.getMonth(), reminder.date.getDate(), 
				reminder.date.getHours(), reminder.date.getMinutes() );
			if ( reminder.allDayEvent ) {
				newDate.setHours( 0, 0 );
			}
			var mins = 	newDate.getMinutes();
			var alarmMinutes = reminderFox_getAlarmInMinutes( reminder.alarm );
			if ( alarmMinutes != null ) { 
				newDate.setMinutes( mins - alarmMinutes );
				
				var dateString = reminderFox_getDateVariableString( reminder, newDate);
				var timeString = reminderFox_mail_getTimeString(newDate);
						
				var snoozetitle = document.createElement("description");
				snoozetitle.setAttribute("value",  g_reminderFoxBundle.getString("rf.alarm.tooltip.text")   + " " + dateString + ", " + timeString);   
				tooltipItem.appendChild(snoozetitle);	
			}
		}
		
		// add the alarm value to the tooltip  (eg: "alarm: 15 minutes before event")
		var title = document.createElement("description");
		title.setAttribute("value", getAlarmTooltipText( reminder.alarm ));
		tooltipItem.appendChild(title);	
	}
	else {  	 			
		var row = selectedTreeItem.childNodes[0];
		var dateCell = row.childNodes[0];
		var dateCellLabel = dateCell.getAttribute("label");		
		var descCell = row.childNodes[1];
		var descCellLabel = descCell.getAttribute("label");
		var timeCell = row.childNodes[2];
		var timeCellLabel = timeCell.getAttribute("label");			
		var completedDateNode = selectedTreeItem.childNodes[0].childNodes[3];	
		var completedDateLabel = completedDateNode.getAttribute( "label");
	
		var important = false;
		if ( reminder.priority == REMINDER_PRIORITY_IMPORTANT ) {
			important = true;
		}
		
		// see if current instance of reminder is completed
		var completed = false;	
		var reminderDateTime = row.getAttribute(REMINDER_DATE_REF);	
		var reminderInstanceDate = new Date(parseInt(reminderDateTime));		
		
		if  ( reminderFox_isCompletedForDate( reminder, reminderInstanceDate )  ) {
			completed = true;
		}  
		
		addTooltipWithLabel( tooltipItem, "descColLabel", descCellLabel, important, completed );
		
		var dateString = dateCellLabel;
		if ( !reminder.allDayEvent ) {
			dateString = dateString + ", " + timeCellLabel;
		}
		
		if ( reminder.durationTime != null ) {
			var reminderInstanceEndDate = new Date(parseInt(reminderDateTime) + reminder.durationTime);		
			if ( reminder.allDayEvent ) {
				if (reminder.durationTime >86400000 ) {   // 24 * 60 * 60 * 1000 = 1 day in ms
					reminderInstanceEndDate.setDate( reminderInstanceEndDate.getDate() - 1); // -1 enddate offset
					var endDateStr = reminderFox_getDateVariableString( reminder, reminderInstanceEndDate);
					dateString += " - " +  endDateStr;
				}
			}
			else {
				var endTime = reminderFox_mail_getTimeString(reminderInstanceEndDate);
				if (reminderInstanceEndDate.getMonth() == reminderInstanceDate.getMonth() &&
					reminderInstanceEndDate.getDate() == reminderInstanceDate.getDate() ) {
					// same days.. 
					dateString += " - " +  endTime;
				}
				// multiple days
				else { 
					var endDateStr = reminderFox_getDateVariableString( reminder, reminderInstanceEndDate);
					dateString += " - " +  endDateStr + ", " + endTime;
				}
			}
		}
		
		
		addTooltipWithLabel( tooltipItem, "dateColLabel", dateString );
		
		if ( reminder.categories != null && reminder.categories != "" ) {			
			addTooltipWithLabel( tooltipItem, "catColLabel", reminder.categories );
		}
		
		if ( completedDateLabel != null && completedDateLabel != "" ) {		
			addTooltipWithLabel( tooltipItem, "dateCompleted", completedDateLabel );
		}
		
		if ( reminder.location != null && reminder.location != "" ) {			
			addTooltipWithLabel( tooltipItem, null, reminder.location, false, false, g_reminderFoxBundle.getString("rf.add.reminders.tooltip.locaton") );  
		}
		
		if ( reminder.url != null && reminder.url != "" ) {			
			addTooltipWithLabel( tooltipItem, null, reminder.url, false, false, g_reminderFoxBundle.getString("rf.add.reminders.tooltip.url") );
		}				
				
		// add notes to to tooltip (if applicable)		
		// 	  	 	
	 	if ( reminder.notes != null ) {
	  	 	addNotesToTooltip( reminder.notes, tooltipItem );
	   }
	}
   return true;
}


function todoTreeTooltip(event) {
 	var tree = document.getElementById("todoTree");
 	var boxobject = tree.boxObject;
  	boxobject.QueryInterface(Components.interfaces.nsITreeBoxObject);  // cast to treeboxobject to use getRowAt
  	//boxobject.getCellAt(event.clientX, event.clientY, row, column, part);

	var row = {}, column = {}, part = {};
	boxobject.getCellAt(event.clientX, event.clientY, row, column, part);
	
	if (column.value != null && typeof column.value != "string") {
	 	column.value = column.value.id;  
	 }
  
 	var index = tree.boxObject.getRowAt( event.clientX, event.clientY );
 	if ( index == -1 ) {
 		return false; // returning false causes tooltip to not show
 	}
 	var treeChildren = document.getElementById("todoTreechildren");
 	var selectedTreeItem = treeChildren.childNodes[index];
	var todoRefId = selectedTreeItem.childNodes[0].getAttribute(REMINDER_ID_REF);
	var todo =  reminderFox_getTodosById( todoRefId,  getCurrentTodoList() );
 	if ( todo == null ) {
 		return false; // returning false causes tooltip to not show
 	}
 	
 	todo = reminderFox_processReminderDescription(todo,  new Date().getFullYear(), true );	
 	

 	 var tooltipItem = document.getElementById("todoTree-tooltip-box"); 
     while (tooltipItem.hasChildNodes()) {
    	 	tooltipItem.removeChild(tooltipItem.firstChild);
  	 } 	
 	
 	// if this is the alarm column, show the alarm value
	if ( todo.alarm != null && column != null && column.value == "todoAlarmColLabel" ) { 
		// if the alarm is currently snoozed, show the snooze value as well....	
		if ( todo.snoozeTime != null ) { 
			var snoozeAlarmTime = todo.snoozeTime;
			var index = snoozeAlarmTime.indexOf( ';' );
			if ( index != -1 ) {
				snoozeAlarmTime = snoozeAlarmTime.substring( 0, index );				
			}		
			var snoozedate = new Date( parseInt(snoozeAlarmTime));	
			var dateString = reminderFox_getDateVariableString( todo, snoozedate);
			var timeString = reminderFox_mail_getTimeString(snoozedate);

			var snoozetitle = document.createElement("description");
			snoozetitle.setAttribute("value",  g_reminderFoxBundle.getString("rf.alarm.list.tooltip.snooze")  + " " + dateString + ", " + timeString);  
			tooltipItem.appendChild(snoozetitle);	
		}
		
		// add the alarm to the tooltip
		var title = document.createElement("description");
		title.setAttribute("value", getAlarmTooltipText( todo.alarm ));
		tooltipItem.appendChild(title);		
		  
		
		
		
	}
	else {		
		var row = selectedTreeItem.childNodes[0];
		var dateCell = row.childNodes[0];
		var dateCellLabel = dateCell.getAttribute("label");		
		var descCell = row.childNodes[1];
		var descCellLabel = descCell.getAttribute("label");
		var timeCell = row.childNodes[2];
		var timeCellLabel = timeCell.getAttribute("label");	
		var completedDateNode = selectedTreeItem.childNodes[0].childNodes[3];	
		var completedDateLabel = completedDateNode.getAttribute( "label");
		
		var important = false;
		if ( todo.priority == REMINDER_PRIORITY_IMPORTANT ) {
			important = true;
		}
		var completed = false;
		if  ( todo.completedDate != null  ) {
			completed = true;
		}
		addTooltipWithLabel( tooltipItem, "descColLabel", descCellLabel, important, completed );
	
		if ( todo.date != null ) {
			var dateString = dateCellLabel;
			if ( !todo.allDayEvent ) {
				dateString = dateString + ", " + timeCellLabel;
			}
			
			if ( todo.durationTime != null ) {
				var reminderDateTime = row.getAttribute(REMINDER_DATE_REF);	
				if ( reminderDateTime != null ) {
					var reminderInstanceDate = new Date(parseInt(reminderDateTime));		
					var reminderInstanceEndDate = new Date(parseInt(reminderDateTime) + todo.durationTime);		
					if ( todo.allDayEvent ) {
						if (todo.durationTime >86400000 ) {   // 24 * 60 * 60 * 1000 = 1 day in ms
							reminderInstanceEndDate.setDate( reminderInstanceEndDate.getDate() - 1); // -1 enddate offset
							var endDateStr = reminderFox_getDateVariableString( todo, reminderInstanceEndDate);
							dateString += " - " +  endDateStr;
						}
					}
					else {
						var endTime = reminderFox_mail_getTimeString(reminderInstanceEndDate);
						if (reminderInstanceEndDate.getMonth() == reminderInstanceDate.getMonth() &&
							reminderInstanceEndDate.getDate() == reminderInstanceDate.getDate() ) {
							// same days.. 
							dateString += " - " +  endTime;
						}
						// multiple days
						else { 
							var endDateStr = reminderFox_getDateVariableString( todo, reminderInstanceEndDate);
							dateString += " - " +  endDateStr + ", " + endTime;
						}
					}
				}
			}
			
			
			addTooltipWithLabel( tooltipItem, "dateColLabel", dateString );
		}
		
		if ( todo.categories != null && todo.categories != "" ) {			
			addTooltipWithLabel( tooltipItem, "catColLabel", todo.categories );
		}
		
		if ( completedDateLabel != null && completedDateLabel != "" ) {		
			addTooltipWithLabel( tooltipItem, "todoDateCompleted", completedDateLabel );
		}
		
		if ( todo.location != null && todo.location != "" ) {			
			addTooltipWithLabel( tooltipItem, null, todo.location, false, false, g_reminderFoxBundle.getString("rf.add.reminders.tooltip.locaton") );  
		}
		
		if ( todo.url != null && todo.url != "" ) {			
			addTooltipWithLabel( tooltipItem, null, todo.url, false, false, g_reminderFoxBundle.getString("rf.add.reminders.tooltip.url") );
		}				
				
		// add notes to to tooltip (if applicable)		
		// 	  	 	
	 	if ( todo.notes != null ) {
	  	 	addNotesToTooltip( todo.notes, tooltipItem );
	   } 		  		
	}

   return true;
}

function addNotesToTooltip( orignotes, tooltipItem, maxLines ) {
 	var newline = "\n";
 	
 	// replace all tab characters with spaces (otherwise shows up as weird character)
 	var notes = orignotes.replace(new RegExp(/\t/g),"    ");  
 	//var columnLabel = getLabelForColumn( "notesColLabel");
	var separatedString = notes.split(newline);	
	var tooltipWrapLength = 120;
	var remLabel;
	var headerAdded = false;
	var maxLinesReached = false;
	var numberOfLinesAdded = 0;
	for ( var i = 0; i < separatedString.length && !maxLinesReached; i++ ) {
		var noteLine = separatedString[i];
		while ( noteLine.length > tooltipWrapLength && !maxLinesReached ) {		
			// go back to last whitespace
			var lastIndex = noteLine.lastIndexOf( ' ', tooltipWrapLength );
			var forceLineBreak = false;
			if ( lastIndex == -1 ) {
				forceLineBreak = true;
		    	lastIndex = tooltipWrapLength + 1;
			}
			if ( lastIndex != -1 ) {
			    var curStr = noteLine.substring( 0, lastIndex );				    	    			   
			    if ( !headerAdded ) { // first row, add column header name			    
					addTooltipWithLabel( tooltipItem, "notesColLabel", curStr );
					numberOfLinesAdded++;
					headerAdded = true;
				}	   
				else {
					remLabel = document.createElement("description");		
					remLabel.setAttribute("value", curStr);
					tooltipItem.appendChild(remLabel);
					numberOfLinesAdded++;
					if ( maxLines != null && numberOfLinesAdded >= maxLines ) {
						maxLinesReached = true;
					}
				}
			}
			var startIndex;
			if ( forceLineBreak ) {
				startIndex = lastIndex;
			}
			else {
				startIndex = lastIndex + 1;
			}
			noteLine = noteLine.substring( startIndex );		  										
		}			

	    if ( !headerAdded ) { // first row, add column header name			    
			addTooltipWithLabel( tooltipItem, "notesColLabel", noteLine );
			numberOfLinesAdded++;
			headerAdded = true;
		}			
		else {
			remLabel = document.createElement("description");
			remLabel.setAttribute("value", noteLine);
			tooltipItem.appendChild(remLabel);
			
			numberOfLinesAdded++;
			if ( maxLines != null && numberOfLinesAdded >= maxLines ) {
				maxLinesReached = true;
			}
		}
	}
	
	// notes are truncated - add indicator
	if ( maxLinesReached ) {
  	 	var notesTruncatedLabel = document.createElement("description");
		notesTruncatedLabel.setAttribute("value", "...");
		tooltipItem.appendChild(notesTruncatedLabel);
	}
		
}	  	 				

function userMoveTodoToReminderList(eventTarget) {
	var selectedTodos = getAllSelectedTodos();
	for ( var i = 0; i < selectedTodos.length; i++ ) {		
		var movedTodo = selectedTodos[i];	

		var newReminder = reminderFox_convertTodoToReminder( movedTodo);
		
		removeTodo(movedTodo);
	
		// add reminder in sorted order...
		var reminders = reminderFox_getReminderEvents();				
		var sortedIndex = reminderFox_getSortedIndexOfNewReminder( reminders, newReminder, false );
		reminderFox_insertIntoArray( reminders, newReminder, sortedIndex );
	
		createListItem(newReminder);  // update UI list
	}
	refreshCalendar();

	modifiedReminders();	    	
}

function getAlarmTooltipText( alarmTime)  {	 
	var result;
	var alarmIndex1 = alarmTime.indexOf( "-PT" );
	if ( alarmIndex1 != -1 ) {
		var alarmIndex2 = alarmTime.indexOf( "M", alarmIndex1 );
		if ( alarmIndex2 != -1 ) {
			alarmTime = alarmTime.substring( alarmIndex1 + "-PT".length, alarmIndex2 );		
			result = "(" + g_reminderFoxBundle.getString("rf.reminderoptions.alarm")  + ": " + 
				 alarmTime + " " + g_reminderFoxBundle.getString("rf.reminderoptions.notify.minutes.label") + " " +
				 g_reminderFoxBundle.getString("rf.reminderoptions.notify.before.label") + ")";
				 
		}
		else {
			alarmIndex2 = alarmTime.indexOf( "H", alarmIndex1 );
			if ( alarmIndex2 != -1 ) {
				alarmTime = alarmTime.substring( alarmIndex1 + "-PT".length, alarmIndex2 );		
				result = "(" + g_reminderFoxBundle.getString("rf.reminderoptions.alarm")  + ": " + 
					 alarmTime + " " + g_reminderFoxBundle.getString("rf.reminderoptions.notify.hours.label") + " " +
					 g_reminderFoxBundle.getString("rf.reminderoptions.notify.before.label") + ")";
			}	
		}	
	}
	else {
		alarmIndex1 = alarmTime.indexOf( "-P" );
		if ( alarmIndex1 != -1 ) {
			var alarmIndex2 = alarmTime.indexOf( "D", alarmIndex1 );
			if ( alarmIndex2 != -1 ) {
				alarmTime = alarmTime.substring( alarmIndex1 + "-P".length, alarmIndex2 );		
				result = parseInt( alarmTime ) * 24 * 60;	
				result = "(" + g_reminderFoxBundle.getString("rf.reminderoptions.alarm")  + ": " + 
					 alarmTime + " " + g_reminderFoxBundle.getString("rf.reminderoptions.notify.days.label") + " " +
				 	g_reminderFoxBundle.getString("rf.reminderoptions.notify.before.label") + ")";
			}
		 }
	}		
	return result;
}

function userMoveToTodoList(eventTarget) {
	var targetTodoListName =  eventTarget.getAttribute( "label" );
	var selectedTodos = getAllSelectedTodos();
   var messageIDtagging = (selectedTodos.length == 1 ) ? true : false;
	for ( var i = 0; i < selectedTodos.length; i++ ) {		
		var movedTodo = selectedTodos[i];		
	
		if ( movedTodo.date != null ) { // could want to move to a reminder
			var tabList = document.getElementById("tabList");	
			var tablistItem = tabList.childNodes[0];	  // get first tab (reminders)
			var tabLabel = tablistItem.getAttribute("label");		
			
			if ( tabLabel == targetTodoListName) {
				userMoveTodoToReminderList(eventTarget);
				return;
			}
		}	
		// if moving to ToDo's, use special "ToDo's" id (as label could be another language)
		var tabList = document.getElementById("tabList");	
		var tablistItem = tabList.childNodes[1];	  // get second tab -- "ToDo's"
		var tabLabel = tablistItem.getAttribute("label");		
		if ( tabLabel == targetTodoListName) {
			targetTodoListName = REMINDER_FOX_DEFAULT_TODOS_CATEGORY;
		}	
			
		var todosArr =	reminderFox_getReminderTodos();
		var todos = todosArr[targetTodoListName];
		if ( todos == null ) {
			todos = new Array();
			todosArr[targetTodoListName] = todos;
		}	
		removeTodo(movedTodo, messageIDtagging);
		
		var sortedIndex = reminderFox_getSortedIndexOfNewTodo(todos, movedTodo );
		reminderFox_insertIntoArray( todos, movedTodo, sortedIndex );
	}
	refreshCalendar();
  	modifiedReminders();
}

function activateTodoContext(event) {
	var tree = document.getElementById("todoTree");
	document.popupNode = tree;
	
	var selectedTreeItemIndex = document.getElementById("todoTree").currentIndex;
	var treeChildren = document.getElementById("todoTreechildren");
	var contextMenu = document.getElementById("todo-treechildren-contextmenu");	
	var currentTodo = getTodoForSelectedItem( );
	if ( treeChildren == null || selectedTreeItemIndex == -1 || treeChildren.childNodes.length == 0 || currentTodo == null ) {
		for ( var i = 0; i < contextMenu.childNodes.length; i++ ) {
			contextMenu.childNodes[i].setAttribute( "disabled", true );
		}
		return;
	}
	else { 
		// enable all child menu items
		for ( var i = 0; i < contextMenu.childNodes.length; i++ ) {
			contextMenu.childNodes[i].removeAttribute( "disabled" );
		}		
	}
	
	
	var multipleTodosSelected = false;
	var selectedTodos = getAllSelectedTodos();
	if ( selectedTodos.length > 1 ) { 
		multipleTodosSelected = true;
	}
	
	var treechildrenContextmenuEdit = document.getElementById("treechildren-contextmenu-edit2");	
	if ( multipleTodosSelected ) { 
		// if multiple reminders selected, disable Edit		
		treechildrenContextmenuEdit.setAttribute( "disabled", true );
	}
	else {
			treechildrenContextmenuEdit.removeAttribute( "disabled" );
	}
	
	
	// show current lists...
	var moveToList = document.getElementById("treechildren-contextmenu-moveToList-popup");	
	while (moveToList.hasChildNodes()) {
		 moveToList.removeChild(moveToList.firstChild);
	}
	var tabList = document.getElementById("tabList");	
	var tab =	tabList.selectedItem;
	var tabIndex =	tabList.selectedIndex;

	var index = tab.id.indexOf( ':' );
	if ( tabIndex <= 1 || index == -1 ) {
		name = REMINDER_FOX_DEFAULT_TODOS_CATEGORY;
	}
	else {
		name = tab.id.substring( index +1 , tab.id.length );
	}
	
	var i = 0;
	if ( currentTodo.date == null ) {
		i = 1;   // if no date on the ToDo, don't allow to move to a reminder
	}
	var subscriptions = reminderFox_getSubscriptions();
	for ( ; i < tabList.childNodes.length; i++ ) {  
		var tablistItem = tabList.childNodes[i];	
		var tabLabel = tablistItem.getAttribute("label");
		if ( tabLabel != name &&  subscriptions[tabLabel] == null ) {  // ignore subscribed calendars
			var menuItem = document.createElement("menuitem");
			menuItem.setAttribute( "label", tabLabel );
			menuItem.setAttribute( "oncommand", "userMoveToTodoList(event.target)");
			moveToList.appendChild(menuItem);
		}
	}	
	
	// modify context menu depending on Important reminder status
	var contextMenuImportant = document.getElementById("treechildren-contextmenu-important2");	
	if ( currentTodo.priority != REMINDER_PRIORITY_IMPORTANT ) {
		contextMenuImportant.setAttribute("checked", "false");	
	}
	else {
		contextMenuImportant.setAttribute("checked", "true");	
	}	
	
	var contextMenuComplete = document.getElementById("treechildren-contextmenu-markAsComplete2");	
	if ( currentTodo.completedDate != null  ) {
			contextMenuComplete.setAttribute("checked", "true");	
	}
	else {
		contextMenuComplete.setAttribute("checked", "false");	
	}	


	var contextMenuShowInTooltip = document.getElementById("treechildren-contextmenu-showInTooltip");	
	if ( currentTodo.showInTooltip ) {
		contextMenuShowInTooltip.setAttribute("checked", "true");	
	}
	else {
		contextMenuShowInTooltip.setAttribute("checked", "false");	
	}

	// disable moveUp/moveDown if that option isn't available
	var moveUpMenu = document.getElementById("treechildren-contextmenu-moveUp");		

	var isFirst = 	isFirstTodoSelected();
	if ( isFirst ) {
		moveUpMenu.setAttribute( "disabled", true );
	}
	else {
		moveUpMenu.setAttribute( "disabled", false );
	}
	
	var moveDownMenu = document.getElementById("treechildren-contextmenu-moveDown");	
	if ( isLastTodoSelected() ) {
		moveDownMenu.setAttribute( "disabled", true );
	}
	else {
		moveDownMenu.setAttribute( "disabled", false );
	}
	
	// If reminder is associated with an email, show the View Mail context menu item.  Otherwise, do not.
    var showMail = document.getElementById("treechildren-contextmenu-showMail2");	
    if ( showMail != null ) {
		if (!reminderFox_isMailEvent(currentTodo) ) {
			showMail.setAttribute("hidden", "true");	
		}
		else {
			showMail.setAttribute("hidden", "false");	
		}
	}	
	
	if (getAllSelectedTodos().length == 0) {
		document.getElementById("treechildren-contextmenu-sendTodos").setAttribute("disabled", "true");
	}
		
}


function processKeyPressedOnReminderTree(event) {
	if (event.keyCode == 46 || event.keyCode == 8)   // 46 =  delete key; 8 = backspace (to handle Mac 'Delete')
		userDeleteReminder();
	else if (event.keyCode == 13) // return
		editReminder();
	else if (event.charCode == 32) {	// space bar
		// fun note: if I don't call this in a settimeout, this will crash firefox (yay!).  This 
		// happens if you have a column sorted and hit the spacebar to run this evnet.  
		// In createListItemSorted when it is adding the elements for the tree item, after 
		// 10 attributes it crashes.  No idea why.  
		setTimeout( toggleMarkAsComplete, 1 );	
	}		
}

function processKeyPressedOnTodoTree(event) {
	if (event.keyCode == 46)   // delete key
		userDeleteTodo();
	else if (event.keyCode == 13)  // return
		editTodo();
	else if (event.charCode == 32) {    // space bar
		setTimeout( toggleTodoMarkAsComplete, 1 );	
	}
}



function editReminder() {
	var selectedTreeItemIndex = document.getElementById("reminderTree").currentIndex;
	var treeChildren = document.getElementById("treechildren");
	  
	if ( selectedTreeItemIndex == -1 ) {
		return;
	}
	
	var selectedTreeItem = treeChildren.childNodes[selectedTreeItemIndex];
	if (  selectedTreeItem == null ) {
		return;
	}

	var currentReminder = getReminderForSelectedItem(); 
	var originalReminder = reminderFox_cloneReminderFoxEvent(currentReminder);

	var newOptions = { reminder: currentReminder, editing:  true,  addReminder: false, showMail: false,  readonly: isSubscribedCalendarTabSelected() };
	window.openDialog("chrome://reminderfox/content/editing/reminderOptionsDialog.xul",
			"window:reminderFoxReminderOptionsDialog", "chrome,resizable,modal", newOptions);

//   3.2.2.1 Rescheduling an Event:
//   A rescheduled event involves time or recurrence intervals 
//   and possibly the location or description
	rmFx_iCalReschedule(originalReminder, currentReminder);
	
	if ( newOptions.showMail ) {		 	
		reminderFox_displayMailbyMsgID(currentReminder);	
		editReminder();
		return;
	}

	if ( newOptions.addReminder ) {
		currentReminder = newOptions.reminder;
		
		if ( originalReminder.date.getFullYear() != currentReminder.date.getFullYear() ||
			originalReminder.date.getMonth() != currentReminder.date.getMonth() ||
			originalReminder.date.getDate() != currentReminder.date.getDate() ||
			originalReminder.date.getHours() != currentReminder.date.getHours() ||
			originalReminder.date.getMinutes() != currentReminder.date.getMinutes() ||  
			originalReminder.recurrence.endDate != currentReminder.recurrence.endDate || 
			originalReminder.recurrence.byDay !=  currentReminder.recurrence.byDay || 
			originalReminder.recurrence.interval != currentReminder.recurrence.interval ) {
				// if the date has changed (or recurrence), treat as a new reminder.  This is because 
				// We want to re-add in the proper sorted order into the list of reminders
				
				removeListItemsForReminder(originalReminder); 
				// remove from model list
				var reminders = reminderFox_getReminderEvents();	
				for( var i = 0; i < reminders.length; i++) {
					if ( reminders[i].id == originalReminder.id ) {
						reminderFox_removeElement(reminders, i);
						break;
					}
				}
	
				// add reminder in sorted order...
				reminders = reminderFox_getReminderEvents();					
				if ( currentReminder.remindUntilCompleted != REMINDERFOX_REMIND_UNTIL_COMPLETE_NONE ) {
	     			currentReminder.remindUntilCompleted = REMINDERFOX_REMIND_UNTIL_COMPLETE_TO_BE_MARKED;
	     		}				
				var sortedIndex = reminderFox_getSortedIndexOfNewReminder( reminders, currentReminder, false );
				reminderFox_insertIntoArray( reminders, currentReminder, sortedIndex );
				
				currentReminder.snoozeTime = null;  			
				createListItem(currentReminder);			
			}
			// if the recurrence has changed, then we want to update the list as the dates may have 
			// changed
			else 	if ( originalReminder.recurrence.type != currentReminder.recurrence.type ) {
				removeListItemsForReminder(originalReminder);
				createListItem(currentReminder);			
			}
		
			var currentDate = oeDatePicker.gSelectedDate;
			if ( currentDate == null ) {
				currentDate = new Date();
			}	
			
			var newDate = new Date();
			if ( currentReminder.alarm != null ) {
				currentReminder.alarmLastAcknowledge = newDate.getTime();
				// if there's a snooze... and lastack > snooze, erase snooze...  this means...  well it should be if date changed at all, then need to clear snooze...
			}
			currentReminder.lastModified = reminderFox_getDateAsString(newDate );
			var reminder = reminderFox_processReminderDescription(currentReminder,  currentDate.getFullYear(), false);		
			var modified = updateReminderInList( reminder );
			sortReminderIfNeccessary( currentReminder.id); 

			refreshCalendar(false, true);
			modifiedReminders();
		}
}

function reminderFox_copyReminder(originalReminder, isTodo) {
	var currentDate = new Date();
	var newReminderFoxEvent = null;
	if ( !isTodo ) {
		newReminderFoxEvent = reminderFox_cloneReminderFoxEvent(originalReminder);
	}
	else {
		newReminderFoxEvent = reminderFox_cloneReminderFoxTodo(originalReminder);
	}
	var newId =reminderFox_generateUniqueReminderId(currentDate );
	newReminderFoxEvent.id =newId;
	newReminderFoxEvent.completedDate = null;
	newReminderFoxEvent.snoozeTime = null;
	if ( newReminderFoxEvent.alarm != null ) {
		newReminderFoxEvent.alarmLastAcknowledge = currentDate.getTime();
	}
	newReminderFoxEvent.lastModified = reminderFox_getDateAsString(currentDate );
	
	if ( newReminderFoxEvent.remindUntilCompleted ==  REMINDERFOX_REMIND_UNTIL_COMPLETE_MARKED ) { 
		newReminderFoxEvent.remindUntilCompleted = REMINDERFOX_REMIND_UNTIL_COMPLETE_TO_BE_MARKED;
	}
	
	return newReminderFoxEvent;
	
}

function copyReminder() {
	var selectedTreeItemIndex = document.getElementById("reminderTree").currentIndex;
	var treeChildren = document.getElementById("treechildren");
	  
	if ( selectedTreeItemIndex == -1 ) {
		return;
	}
	
	var selectedTreeItem = treeChildren.childNodes[selectedTreeItemIndex];
	if (  selectedTreeItem == null ) {
		return;
	}

	var currentReminder = getReminderForSelectedItem(); 
	
	var newCopyOfReminder = reminderFox_copyReminder( currentReminder );
	
	addReminder( true, newCopyOfReminder );
}

function copyTodo() {
	var currentTodo = getTodoForSelectedItem( );
	if ( currentTodo == null ) {
		return;
	}
	
	var newCopyOfTodo = reminderFox_copyReminder( currentTodo , true);
	
	addTodo( true, newCopyOfTodo );
}

function userDeleteReminder() {
	var selectedReminders = getAllSelectedReminders();
	
	if ( selectedReminders.length == 1 && 
			 (selectedReminders[0].recurrence.type == REMINDER_RECURRENCE_MONTHLY_DATE ||
			  selectedReminders[0].recurrence.type == REMINDER_RECURRENCE_MONTHLY_DAY ||
			  selectedReminders[0].recurrence.type == REMINDER_RECURRENCE_WEEKLY ||
			  selectedReminders[0].recurrence.type == REMINDER_RECURRENCE_DAILY) ) {
    	removeReminder(selectedReminders[0], true);			
	}
	else {
		var deleteDescription  = null;
		var reminderTitle = null;
		if ( selectedReminders.length == 1 ) {
			deleteDescription = g_reminderFoxBundle.getString("rf.add.deleteReminder.description") + "\n";
			reminderTitle = g_reminderFoxBundle.getString("rf.add.deleteReminder.title");
		}
		else {
			deleteDescription = g_reminderFoxBundle.getString("rf.add.deleteReminders.description") + "\n";
			reminderTitle = g_reminderFoxBundle.getString("rf.add.deleteReminders.title");
		}
		
		
		var reminderDateLabelArray = new Array();  // store the date label and delete date before we start deleting the reminders, as then the selected indices get shifted
		var reminderDeleteDateArray = new Array();
      var messageIDtagging = (selectedReminders.length == 1 ) ? true : false;
		for ( var i = 0; i < selectedReminders.length; i++ ) {		
			var currentReminder = selectedReminders[i];
			var deleteDate = getInstanceDateOfLastSelected( currentReminder ); 
			var dateLabel = reminderFox_getDateVariableString( currentReminder, deleteDate );
			reminderDateLabelArray[currentReminder.id]= dateLabel;						
			reminderDeleteDateArray[currentReminder.id]= deleteDate;
			var descLabel = currentReminder.summary;
			deleteDescription += dateLabel + ": " + descLabel + "\n";
		}
			
		var nsIPromptService = Components.interfaces.nsIPromptService;
		var nsPrompt_CONTRACTID = "@mozilla.org/embedcomp/prompt-service;1";
		var gPromptService = Components.classes[nsPrompt_CONTRACTID].getService(nsIPromptService);
		if (gPromptService.confirm(window,
			reminderTitle,  
			deleteDescription)) {
			
			for ( var i = 0; i < selectedReminders.length; i++ ) {		
				var currentReminder = selectedReminders[i];				
	     		removeReminder(currentReminder, true, 
	     		    reminderDeleteDateArray[currentReminder.id], 
	     		    reminderDateLabelArray[currentReminder.id],
	     		    messageIDtagging);
			}		
	     }
	}
	
	refreshCalendar(false, true);			
	modifiedReminders();
}




function userMoveReminderToTodo(eventTarget) {
	var targetTodoListName =  eventTarget.getAttribute( "label" );
	
	// if moving to ToDo's, use special "ToDo's" id (as label could be another language)
	var tabList = document.getElementById("tabList");	
	var tablistItem = tabList.childNodes[1];	  // get second tab -- "ToDo's"
	var tabLabel = tablistItem.getAttribute("label");		
	if ( tabLabel == targetTodoListName) {
		targetTodoListName = REMINDER_FOX_DEFAULT_TODOS_CATEGORY;
	}
	
	var reminderItem = tabList.childNodes[0];	  // get second tab -- "ToDo's"
	var remindertabLabel = reminderItem.getAttribute("label");		
	if ( remindertabLabel == targetTodoListName) {
		//targetTodoListName = REMINDER_FOX_DEFAULT_TODOS_CATEGORY;
		// dealing with reminders...
		
		var selectedReminders = getAllSelectedReminders();
      var messageIDtagging = (selectedReminders.length == 1 ) ? true : false;
		for ( var i = 0; i < selectedReminders.length; i++ ) {		
			var currentReminder = selectedReminders[i];
		//	var newTodo = reminderFox_convertReminderToTodo( currentReminder );
			var newReminder = reminderFox_cloneReminderFoxEvent(currentReminder);
			// remove from reminders
		 	removeReminder(currentReminder, null, null, null, messageIDtagging);
							
			var reminders = reminderFox_getReminderEvents();				
			var sortedIndex = reminderFox_getSortedIndexOfNewReminder( reminders, newReminder, false );
			reminderFox_insertIntoArray( reminders, newReminder, sortedIndex );
	
			//createListItem(newReminder);  // update UI list

		}	
		// if todo list is selected (has child nodes, need to add a list item to it)
		reminderFoxTabDirtied = true;
		
		refreshCalendar();
	
		modifiedReminders();	    	    		
		
		return;
		
		
	}
	
	
	var todosArr =	reminderFox_getReminderTodos();
	var todos = todosArr[targetTodoListName];
	if ( todos == null ) {
		todos = new Array();
		todosArr[targetTodoListName] = todos;
	}		
	
	var selectedReminders = getAllSelectedReminders();
   var messageIDtagging = (selectedReminders.length == 1 ) ? true : false;
	for ( var i = 0; i < selectedReminders.length; i++ ) {		
		var currentReminder = selectedReminders[i];
		var newTodo = reminderFox_convertReminderToTodo( currentReminder );
		
		// remove from reminders
		removeReminder(currentReminder, null, null, null, messageIDtagging);
						
		var sortedIndex = reminderFox_getSortedIndexOfNewTodo(todos, newTodo );
		reminderFox_insertIntoArray( todos, newTodo, sortedIndex );    				
	}	
	// if todo list is selected (has child nodes, need to add a list item to it)
	reminderFoxTabDirtied = true;
	
	refreshCalendar();

	modifiedReminders();	    	    		

}

function userDeleteTodo() {
	var deleteDescription = g_reminderFoxBundle.getString("rf.add.deleteToDo.description") + "\n  ";

	var selectedTodos = getAllSelectedTodos();
	for ( var i = 0; i < selectedTodos.length; i++ ) {		
		var currentTodo = selectedTodos[i];
		var dateLabel = "";
		if ( currentTodo.date != null ) {
			 dateLabel = reminderFox_getDateVariableString( currentTodo, currentTodo.date ) + ": ";
		}		
		var descLabel = currentTodo.summary;
		deleteDescription += dateLabel  + descLabel + "\n";
	}
	
	var nsIPromptService = Components.interfaces.nsIPromptService;
	var nsPrompt_CONTRACTID = "@mozilla.org/embedcomp/prompt-service;1";
	var gPromptService = Components.classes[nsPrompt_CONTRACTID].getService(nsIPromptService);
	if (gPromptService.confirm(window,
			g_reminderFoxBundle.getString("rf.add.deleteToDo.title"),
			deleteDescription  )) {

		var selectedTodos = getAllSelectedTodos();
		for ( var i = 0; i < selectedTodos.length; i++ ) {		
			var currentTodo = selectedTodos[i];
     		removeTodo(currentTodo);
		}
  		modifiedReminders();
     }
     refreshCalendar(true, false);
}

function getTreeItemIndexForTodo( todo ) {
	var treeChildren = document.getElementById("todoTreechildren");
	var treeitems = treeChildren.childNodes;
	for (var i=treeitems.length - 1; i >= 0; i--) {
		var item = treeitems[i];
		var row = item.childNodes[0];
		var reminderRefId = row.getAttribute(REMINDER_ID_REF);	
		if ( reminderRefId == todo.id ) {			
			//return item;
			return i;
		}
	}
	return -1;
}


function moveTodoUp() {
	if ( !isFirstTodoSelected( ) ) {
		var oldIndices = getAllSelectedTodoIndices();
		var todos = getCurrentTodoList();
		var treeChildren = document.getElementById("todoTreechildren");
		for ( var k = 0; k < oldIndices.length; k++ ) {
			var index = oldIndices[k];		
			var selectedTreeItem = treeChildren.childNodes[index];
			var currentTodoRefId = selectedTreeItem.childNodes[0].getAttribute(REMINDER_ID_REF);
			var currentTodo =  reminderFox_getTodosById( currentTodoRefId, 	todos);
		
			if ( index > 0 ) {
				var previousIndex = index -1;				
				var previousselectedTreeItem = treeChildren.childNodes[previousIndex];
				var todoRefId = previousselectedTreeItem.childNodes[0].getAttribute(REMINDER_ID_REF);

				// get current index inside of todo array in memory
				var i;
				var found = false;
				for (  i = 0; i < todos.length; i++ ) {
					if ( todos[i].id == todoRefId ) {
						found = true;
						break;
					}
				}
				
				if ( found && i >= 0 ) { 
					//var newIndex = getPreviousTodoIndex(todos, i );  // insert before old position
					var newIndex = i;
					var newTodo =	reminderFox_cloneReminderFoxTodo( currentTodo );
					var selectedTreeItemIndex = getTreeItemIndexForTodo( newTodo );
					removeTodo(currentTodo);
						
					reminderFox_insertIntoArray( todos, newTodo, newIndex );		
					
					var newListIndex = selectedTreeItemIndex - 1;
					createTodoListItemAtIndex(newTodo,newListIndex );						
				}		
			}
		}
		
		// update the selected items
		var treeSelection = document.getElementById("todoTree").view.selection		
		for ( var k = 0; k < oldIndices.length; k++ ) {
			var index = oldIndices[k];		
			treeSelection.rangedSelect((index-1), (index-1), true);
		}
		
		modifiedReminders();
	}
	
}



function getAllSelectedTodoIndices() {
	var treeChildren = document.getElementById("todoTreechildren");
	var indices = new Array();
	
	var start = new Object();
	var end = new Object();
	var numRanges =  document.getElementById("todoTree").view.selection.getRangeCount();
	
	for (var t = 0; t < numRanges; t++){
	  document.getElementById("todoTree").view.selection.getRangeAt(t,start,end);
	  for (var v = start.value; v <= end.value; v++){
	    	indices[indices.length] = v;
	  }
	}

	return indices;
}


function getAllSelectedReminderIndices() {
	var treeChildren = document.getElementById("treechildren");
	var indices = new Array();
	
	var start = new Object();
	var end = new Object();
	var numRanges =  document.getElementById("reminderTree").view.selection.getRangeCount();
	
	for (var t = 0; t < numRanges; t++){
	  document.getElementById("reminderTree").view.selection.getRangeAt(t,start,end);
	  for (var v = start.value; v <= end.value; v++){
	    	indices[indices.length] = v;
	  }
	}

	return indices;
}


function getNextTodoIndex(todos, lastIndex ) { 
	if ( !HIDE_COMPLETED_ITEMS ) {
		return lastIndex + 1;
	}

	// bypass all completed todos
	var i;
	for (  i = lastIndex + 1; i < todos.length; i++ ) {	
		if ( todos[i].completedDate == null ) {
			break;
			
		}		
	}
	return i;	
}

function getPreviousTodoIndex(todos, lastIndex ) { 
	if ( !HIDE_COMPLETED_ITEMS ) {
		return lastIndex - 1;
	}
	
	// bypass all completed todos
	var i;
	for (  i = lastIndex -1; i >= 0; i-- ) {
		if ( todos[i].completedDate == null ) {
			break;
		}		
	}
	
	return i;	
}

	


function moveTodoDown() {		
	if ( !isLastTodoSelected( ) ) {
		var oldIndices = getAllSelectedTodoIndices();
		var todos = getCurrentTodoList();
		var treeChildren = document.getElementById("todoTreechildren");
		for ( var k = oldIndices.length -1; k >= 0; k-- ) {
			var index = oldIndices[k];		
			var selectedTreeItem = treeChildren.childNodes[index];
			var currentTodoRefId = selectedTreeItem.childNodes[0].getAttribute(REMINDER_ID_REF);
			var currentTodo =  reminderFox_getTodosById( currentTodoRefId, 	todos);

			var nextIndex = index +1;
					
			var nextselectedTreeItem = treeChildren.childNodes[nextIndex];
			var todoRefId = nextselectedTreeItem.childNodes[0].getAttribute(REMINDER_ID_REF);
			
			// get current index inside of todo array in memory
			var i;
			var found = false;
			for (  i = 0; i < todos.length; i++ ) {
				if ( todos[i].id == currentTodo.id ) {
					found = true;
					break;
				}
			}
						
			if ( found ) { 			
				//var newIndex = getNextTodoIndex(todos, i);  // insert after old position (take into account some todos may be hidden as complete)  // actually want index of next VISIBLE todo (use list todos, not memory todos?)
				var newIndex = i + 1;  // insert current selected item into the next index location (thus moving it down in the list)
				var newTodo =	reminderFox_cloneReminderFoxTodo( currentTodo );
				var selectedTreeItemIndex = getTreeItemIndexForTodo( newTodo );			
				
				removeTodo(currentTodo, false /*messageIDtagging*/);
								
				reminderFox_insertIntoArray( todos, newTodo, newIndex );							
	
				var newListIndex = selectedTreeItemIndex + 1;
				createTodoListItemAtIndex(newTodo,newListIndex );
			}
		}
	
		var treeSelection = document.getElementById("todoTree").view.selection		
		for ( var k = 0; k < oldIndices.length; k++ ) {
			var index = oldIndices[k];		
			treeSelection.rangedSelect((index+1), (index+1), true);
		}
		
		modifiedReminders();
	}
}


function toggleTodoImportantFlag() {
	var selectedTodos = getAllSelectedTodos();

	for ( var i = 0; i < selectedTodos.length; i++ ) {		
		var currentTodo = selectedTodos[i];
		if ( currentTodo.priority == REMINDER_PRIORITY_NORMAL) { 
			currentTodo.priority = REMINDER_PRIORITY_IMPORTANT;
		}
		else {
			currentTodo.priority = REMINDER_PRIORITY_NORMAL;
		}
		
		var modified = updateTodoInList( currentTodo );
	}
	modifiedReminders();
	refreshCalendar(true, true);
}

function getReminderForSelectedItem() {
	var selectedTreeItemIndex = document.getElementById("reminderTree").currentIndex;
	if ( selectedTreeItemIndex != -1 ) {
		var treeChildren = document.getElementById("treechildren");
		var selectedTreeItem = treeChildren.childNodes[selectedTreeItemIndex];
		if (selectedTreeItem != null) {
			var reminderRefId = selectedTreeItem.childNodes[0].getAttribute(REMINDER_ID_REF);
			return reminderFox_getRemindersById(reminderRefId, getCurrentReminderList());
		}
	}
	else {
		return null;
	}
}

function selectReminderById( reminderID) {
	//reminderFox_logMessageLevel("in selectReminderById: " + reminderID, REMINDER_FOX_LOG_LEVEL_DEBUG);
	// make sure reminder list is selected
	var tabList = document.getElementById("tabList");	
	var tablistItem = tabList.childNodes[0];
	if ( tabList.selectedItem != tablistItem ) {
		tabList.selectedItem = tablistItem;
	}
	
	var treeChildren = document.getElementById("treechildren");
	var treeitems = treeChildren.childNodes;
	for (var i=0; i < treeitems.length; i++) {
		var item = treeitems[i];		
		var row = item.childNodes[0];
		var reminderRefId = row.getAttribute(REMINDER_ID_REF);	
		if ( reminderRefId ==reminderID ) {
//			reminderFox_logMessageLevel("in selectReminderById 2h-b: i = " + i  + "; -document.getElementById(reminderTree).currentIndex:  " +
//				document.getElementById("reminderTree").currentIndex, REMINDER_FOX_LOG_LEVEL_DEBUG);
			try { 
				document.getElementById("reminderTree").currentIndex = i;
				var treeSelection = document.getElementById("reminderTree").view.selection	 	
				try {
					treeSelection.select(i);
				}
				catch( e ) {
					reminderFox_logMessageLevel( "Error in selectReminderById1: " +
							e.message   , REMINDER_FOX_LOG_LEVEL_INFO);  //TODO
					reminderFox_logMessageLevel( "Error in selectReminderById1: " +
							e.message   , REMINDER_FOX_LOG_LEVEL_DEBUG);  //TODO
				}
				// make sure that newly selected row is shown in scroll pane
				var value = document.getElementById("treeparent").value;
			  	var tree = document.getElementById("reminderTree");			
				var boxobject = tree.boxObject;
				boxobject.QueryInterface(Components.interfaces.nsITreeBoxObject);
				// make sure it shows up at the top if possible
				var first = boxobject.getFirstVisibleRow();
				var last = boxobject.getLastVisibleRow();
				if ( i < first || i > last ) {	
					boxobject.scrollToRow(treeitems.length - 1);
					boxobject.scrollToRow(treeitems.length - 9);
				}
				var previousReminderOffset = 3;
				if ( i < previousReminderOffset ) { 
					boxobject.ensureRowIsVisible(i);
				}
				else {
					boxobject.ensureRowIsVisible(i  - previousReminderOffset);
				}	
			}
			catch ( e ) { 
				reminderFox_logMessageLevel( "Error in selectReminderById TOTAL: " +
										e.message   , REMINDER_FOX_LOG_LEVEL_INFO);  //TODO
				reminderFox_logMessageLevel( "Error in selectReminderById TOTAL: " +
										e.message   , REMINDER_FOX_LOG_LEVEL_DEBUG);  //TODO
			}
			break;
		}
	}
//	reminderFox_logMessageLevel("End selectReminderById", REMINDER_FOX_LOG_LEVEL_DEBUG);

}


function selectTodoById( todoListName, reminderID) {
	var tabList = document.getElementById("tabList");	
	
	for ( var i = 1; i < tabList.childNodes.length; i++ ) {  // i =1, because we want to skip reminders
		var tablistItem = tabList.childNodes[i];	
		var tabLabel = tablistItem.getAttribute("label");
		if ( tabLabel == todoListName) {
			tabList.selectedItem = tablistItem;
			var treeChildren = document.getElementById("todoTreechildren");
			var treeitems = treeChildren.childNodes;
			for (var i=0; i < treeitems.length; i++) {
				var item = treeitems[i];		
				var row = item.childNodes[0];
				var reminderRefId = row.getAttribute(REMINDER_ID_REF);	
				if ( reminderRefId ==reminderID ) {
					document.getElementById("todoTree").currentIndex = i;
					var treeSelection = document.getElementById("todoTree").view.selection		
					try {
						treeSelection.select(i);
					}
					catch( e ) {
						reminderFox_logMessageLevel( "Error in selectReminderById1: " +
								e.message   , REMINDER_FOX_LOG_LEVEL_INFO);  //TODO
						reminderFox_logMessageLevel( "Error in selectReminderById1: " +
								e.message   , REMINDER_FOX_LOG_LEVEL_DEBUG);  //TODO
					}
					
					// make sure that newly selected row is shown in scroll pane
					var value = document.getElementById("treeparent").value;
				  	var tree = document.getElementById("todoTree");			
					var boxobject = tree.boxObject;
					boxobject.QueryInterface(Components.interfaces.nsITreeBoxObject);
		
					// make sure it shows up at the top if possible
					var first = boxobject.getFirstVisibleRow();
					var last = boxobject.getLastVisibleRow();
					if ( i < first || i > last ) {	
						boxobject.scrollToRow(treeitems.length - 1);
						boxobject.scrollToRow(treeitems.length - 9);
					}
										
					var previousReminderOffset = 3;
					if ( i < previousReminderOffset ) { 
						boxobject.ensureRowIsVisible(i);
					}
					else {
						boxobject.ensureRowIsVisible(i  - previousReminderOffset);
					}	
					break;
				}
			}
			break;
			
		}
	}		
	
	

}


function getTodoForSelectedItem() {
	var selectedTreeItemIndex = document.getElementById("todoTree").currentIndex;
	if ( selectedTreeItemIndex != -1 ) {
		var treeChildren = document.getElementById("todoTreechildren");
		var selectedTreeItem = treeChildren.childNodes[selectedTreeItemIndex];
		if ( selectedTreeItem != null ) {
			var todoRefId = selectedTreeItem.childNodes[0].getAttribute(REMINDER_ID_REF);
			return reminderFox_getTodosById( todoRefId, 	getCurrentTodoList());
		}
	}
	return null;
}


function getAllSelectedReminders() {
	var selectedReminders = new Array();
	var treeChildren = document.getElementById("treechildren");
	var selectedIDsHash = {};
	
	var start = new Object();
	var end = new Object();
	var numRanges =  document.getElementById("reminderTree").view.selection.getRangeCount();
	try {  	//gW_backup&delete 
		for (var t = 0; t < numRanges; t++){
		  document.getElementById("reminderTree").view.selection.getRangeAt(t,start,end);
		  	  
		  for (var v = start.value; v <= end.value; v++){
		    	var selectedTreeItem = treeChildren.childNodes[v];
				if (selectedTreeItem != null) {
					var reminderRefId = selectedTreeItem.childNodes[0].getAttribute(REMINDER_ID_REF);
					selectedIDsHash[reminderRefId] = 0;
				}
		  }
		}
		
		// now we have all the unique IDs in a hash (in case the user selected multiple instances of the same reminder)
		// so we go through and get all of those unique reminders
		for ( var n in selectedIDsHash ) {
			var reminderRefId = n;
			var reminder = reminderFox_getRemindersById( reminderRefId, getCurrentReminderList() );	
			selectedReminders[selectedReminders.length] = reminder;
		}	
	} catch (ex) {
		rmFxUtil.dump2Console('error', ex.message + "; getAllSelectedReminders : Error no Reminders returned!");
	}
	
	return selectedReminders;
}

function isFirstTodoSelected() {
	var start = new Object();
	var end = new Object();
	var numRanges =  document.getElementById("todoTree").view.selection.getRangeCount();
	for (var t = 0; t < numRanges; t++){
	  document.getElementById("todoTree").view.selection.getRangeAt(t,start,end);
	  for (var v = start.value; v <= end.value; v++){
	    	if ( v == 0 ) {
	    		return true;
	    	}
	  }
	}
	return false;
}

function isLastTodoSelected() {
	var treeChildren = document.getElementById("todoTreechildren");
	var treeitems = treeChildren.childNodes;
	var treeItemsLastIndex = treeitems.length - 1;
		
	var start = new Object();
	var end = new Object();
	var numRanges =  document.getElementById("todoTree").view.selection.getRangeCount();
	
	for (var t = 0; t < numRanges; t++){
	  document.getElementById("todoTree").view.selection.getRangeAt(t,start,end);
	  for (var v = start.value; v <= end.value; v++){
	    	if ( v == treeItemsLastIndex ) {
	    		return true;
	    	}
	  }
	}
	return false;
}

function getAllSelectedTodos() {
	var selectedTodos = new Array();
	var treeChildren = document.getElementById("todoTreechildren");
	var selectedIDsHash = {};
	
	var start = new Object();
	var end = new Object();
	var numRanges =  document.getElementById("todoTree").view.selection.getRangeCount();
	
	for (var t = 0; t < numRanges; t++){
	  document.getElementById("todoTree").view.selection.getRangeAt(t,start,end);
	  for (var v = start.value; v <= end.value; v++){
	  		if ( v < 0 ||v > treeChildren.childNodes.length-1 ) { 
	  			reminderFox_logMessageLevel("getAllSelectedTodos outside range: " + v + " > nodes: " +
	  				 treeChildren.childNodes.length + tabName, REMINDER_FOX_LOG_LEVEL_DEBUG);
	  		}
	  		else { 
		    	var selectedTreeItem = treeChildren.childNodes[v];
				var reminderRefId = selectedTreeItem.childNodes[0].getAttribute(REMINDER_ID_REF);
				selectedIDsHash[reminderRefId]= 0;
	  		}
	  }
	}
	
	// now we have all the unique IDs in a hash (in case the user selected multiple instances of the same reminder)
	// so we go through and get all of those unique reminders
	for ( var n in selectedIDsHash ) {
		var reminderRefId = n;
		var todo = reminderFox_getTodosById( reminderRefId,  getCurrentTodoList() );		
		selectedTodos[selectedTodos.length] = todo;
	}	
	
	return selectedTodos;
}




function toggleImportantFlag() {
	var selectedReminders = getAllSelectedReminders();
	for ( var i = 0; i < selectedReminders.length; i++ ) {		
		var currentReminder = selectedReminders[i];
		if ( currentReminder.priority == REMINDER_PRIORITY_NORMAL) { 
			currentReminder.priority = REMINDER_PRIORITY_IMPORTANT;
		}
		else {
			currentReminder.priority = REMINDER_PRIORITY_NORMAL;
		}
		var modified = updateReminderInList( currentReminder );
	}
	refreshCalendar(true, true);
}

function updateReminderInList( reminder) {
	var modified = true;
	var treeChildren = document.getElementById("treechildren");
	var todaysDate= new Date();
	var treeitems = treeChildren.childNodes;
	
	var year = oeDatePicker.gSelectedDate.getFullYear();
	if ( year == null ) {
		year = new Date().getFullYear();
	}
	var reminderInstanceDate;
	for (var i=0; i < treeitems.length; i++) {
		var item = treeitems[i];		
		var row = item.childNodes[0];
		var reminderRefId = row.getAttribute(REMINDER_ID_REF);	
		if ( reminderRefId == reminder.id ) {
			// check if reminder.complete and then reminder.date compared to today's date - first one
			// >= today, mark it as complete.  No others... 
			//if ( reminder.completedDate != null  ) {   
				var reminderDateTime = row.getAttribute(REMINDER_DATE_REF);	
				var reminderInstanceDate = new Date(parseInt(reminderDateTime));		
			//}
			updateReminder(  reminder, item, reminderInstanceDate );
		}
	}
	reminder.lastModified = reminderFox_getDateAsString(todaysDate );

	if ( modified ) {
		modifiedReminders();	
	}
	return modified;
}

function getTreeItemForReminder( reminder ) {
	var treeChildren = document.getElementById("treechildren");
	var treeitems = treeChildren.childNodes;
	for (var i=treeitems.length - 1; i >= 0; i--) {
		var item = treeitems[i];
		var row = item.childNodes[0];
		var reminderRefId = row.getAttribute(REMINDER_ID_REF);	
		if ( reminderRefId == reminder.id ) {			
			return item;
		}
	}
	return null;
}

function updateReminder( reminder, selectedTreeItem, reminderInstanceDate) {
	var modified = true;

	if ( selectedTreeItem == null ) {
		selectedTreeItem = getTreeItemForReminder( reminder );
	}

	var dateNode = selectedTreeItem.childNodes[0].childNodes[0];
	var descriptionNode = selectedTreeItem.childNodes[0].childNodes[1];
    var timeNode = selectedTreeItem.childNodes[0].childNodes[2];			
    var completedDateNode = selectedTreeItem.childNodes[0].childNodes[3];			  
	var repeatNode = selectedTreeItem.childNodes[0].childNodes[4];		    
    var completeNode = selectedTreeItem.childNodes[0].childNodes[5];       	
    var remindUntilCompleteNode = selectedTreeItem.childNodes[0].childNodes[6];             		
    var notesNode = selectedTreeItem.childNodes[0].childNodes[7];                 
    var alarmNode = selectedTreeItem.childNodes[0].childNodes[8];    
    var categoryNode = selectedTreeItem.childNodes[0].childNodes[9];    
    var endDateNode = selectedTreeItem.childNodes[0].childNodes[10];     
	var mailNode = selectedTreeItem.childNodes[0].childNodes[11];                  
	
	// update description
	
	var year = oeDatePicker.gSelectedDate.getFullYear();
	if ( year == null ) {
		year = new Date().getFullYear();
	}

	var todaysDate = new Date();
	
	var isToday = reminderFox_compareDates( reminderInstanceDate, todaysDate) == 0 ;
	var isImportant = reminder.priority == REMINDER_PRIORITY_IMPORTANT;
	var isCompleted =  reminderFox_isCompletedForDate( reminder, reminderInstanceDate ) ;

	reminder = reminderFox_processReminderDescription(reminder, year, false);
	descriptionNode.setAttribute( "label", reminder.summary );

	setTextProperties( isToday, isImportant, isCompleted, dateNode, descriptionNode, timeNode );		        
       

		if ( reminder.allDayEvent ) {
			timeNode.setAttribute("label", REMINDER_FOX_TIME_ALL_DAY_LABEL);
		}
		else {
			var time = reminderFox_getAddTimeString(reminder);
			if ( time == null ) {
				timeNode.setAttribute("label", REMINDER_FOX_TIME_ALL_DAY_LABEL);
			}
			else {
				timeNode.setAttribute("label", time);
			}
		}       
		// update once
		if ( reminder.recurrence.type  == REMINDER_RECURRENCE_YEARLY ) {
			repeatNode.setAttribute("label", REPEAT_LABEL_YEARLY);
		}
		else if ( reminder.recurrence.type  == REMINDER_RECURRENCE_YEARLY_DAY ) {
			repeatNode.setAttribute("label", REPEAT_LABEL_YEARLY_DAY);
		}		
		else 	if ( reminder.recurrence.type  == REMINDER_RECURRENCE_MONTHLY_DATE ) {
			repeatNode.setAttribute("label", REPEAT_LABEL_MONTHLY);
		}
		else if ( reminder.recurrence.type  == REMINDER_RECURRENCE_MONTHLY_DAY ) {
			repeatNode.setAttribute("label", REPEAT_LABEL_MONTHLY_DAY);
		}
		else	if ( reminder.recurrence.type  == REMINDER_RECURRENCE_WEEKLY ) {	
			repeatNode.setAttribute("label", REPEAT_LABEL_WEEKLY);
		}
		else	if ( reminder.recurrence.type  == REMINDER_RECURRENCE_DAILY ) {		
			repeatNode.setAttribute("label", REPEAT_LABEL_DAILY);
		}			
		else {		
			repeatNode.setAttribute("label", REPEAT_LABEL_NONE);
		}		
		
       // update complete
      var isCompleted = reminderFox_isCompletedForDate( reminder, reminderInstanceDate );
	  if ( isCompleted )  {
    	   	completeNode.setAttribute("src",REMINDER_FOX_COMPLETED_IMAGE);	
        	 
			if ( useDefaultDate ) {
				var monthAsText = reminderFox_getMonthAsText(reminder.completedDate.getMonth());		
				completedDateNode.setAttribute("label", monthAsText + " " + reminder.completedDate.getDate());
			}
			else {
				completedDateNode.setAttribute("label", reminderFox_getDateVariableString( reminder, reminder.completedDate ) );
			} 	        	 
        }
 		else {
				completeNode.removeAttribute("src");
       	 		completedDateNode.removeAttribute("label");
		}
		
		if ( reminder.endDate != null ) {
			var monthAsText = reminderFox_getMonthAsText(reminder.endDate.getMonth());		
			if ( useDefaultDate ) {
				endDateNode.setAttribute("label", monthAsText + " " + reminder.endDate.getDate());
			}
			else {
				endDateNode.setAttribute("label", reminderFox_getDateVariableString( reminder, reminder.endDate ) );
			}	
		}
		else {
			endDateNode.removeAttribute("label");
		}
		        
         // update remind until complete
         if ( reminder.remindUntilCompleted != REMINDERFOX_REMIND_UNTIL_COMPLETE_NONE ) {
	     	setRemindUntilCompleteColumn( reminder, remindUntilCompleteNode );        	 
         }
		else {
				remindUntilCompleteNode.removeAttribute("src");
		}       

	  	if ( reminder.notes != null ) {
	  	     //  notesNode.setAttribute("properties", "notes");
     		notesNode.setAttribute("src", REMINDER_FOX_NOTES_IMAGE);			
     	}              
		else {
				notesNode.removeAttribute("src");
				//notesNode.removeAttribute("properties");
		}        	
		
		if ( reminder.alarm != null ) {
			if ( reminder.snoozeTime != null && !isCompleted) { 
				alarmNode.setAttribute("src",REMINDER_FOX_ALARM_SNOOZE_IMAGE);		
			}
			else {
	 			alarmNode.setAttribute("src",REMINDER_FOX_ALARM_IMAGE);			
			}				 
		}
		else {
			alarmNode.removeAttribute("src");
		}    			
		
		if ( reminder.categories != null ) {
     		categoryNode.setAttribute("label", reminder.categories);
		}
		else {
			categoryNode.removeAttribute("label");				
		}
		
	  	if ( mailNode != null ) {
			if (reminderFox_isMailEvent(reminder) ) {
     		   mailNode.setAttribute("src", REMINDER_FOX_MAIL_IMAGE);	
	  		}		        
			else {
				mailNode.removeAttribute("src");
			}
	  	}   				 		
}
  
  

  
  
  
function updateTodoInList( todo) {
	var modified = true;
	var treeChildren = document.getElementById("todoTreechildren");
	var treeitems = treeChildren.childNodes;
	for (var i=0; i < treeitems.length; i++) {
		var selectedTreeItem = treeitems[i];		
		var row = selectedTreeItem.childNodes[0];
		var reminderRefId = row.getAttribute(REMINDER_ID_REF);	
		if ( reminderRefId == todo.id ) {						
			var dateNode = selectedTreeItem.childNodes[0].childNodes[0];
			var descriptionNode = selectedTreeItem.childNodes[0].childNodes[1];
			var timeNode = selectedTreeItem.childNodes[0].childNodes[2];
		    var completedDateNode = selectedTreeItem.childNodes[0].childNodes[3];   	
		    var completeNode = selectedTreeItem.childNodes[0].childNodes[4];       	
		    var showInTooltipNode = selectedTreeItem.childNodes[0].childNodes[5];    
		    var notesNode = selectedTreeItem.childNodes[0].childNodes[6];       
			var alarmNode = selectedTreeItem.childNodes[0].childNodes[7];
			var categoryNode = selectedTreeItem.childNodes[0].childNodes[8];       
			var endDateNode = selectedTreeItem.childNodes[0].childNodes[9];      
 		    var mailNode = selectedTreeItem.childNodes[0].childNodes[10];                  
			
			if ( todo.date != null ) {
				var monthAsText = reminderFox_getMonthAsText(todo.date.getMonth());		
				if ( useDefaultDate ) {
					dateNode.setAttribute("label", monthAsText + " " + todo.date.getDate());
				}
				else {
					dateNode.setAttribute("label", reminderFox_getDateVariableString( todo, todo.date ) );
				}	
						
				if (  todo.allDayEvent ) {
					timeNode.setAttribute("label", REMINDER_FOX_TIME_ALL_DAY_LABEL);
				}
				else {
					var time = reminderFox_getAddTimeString(todo);
					if ( time == null ) {
						timeNode.setAttribute("label", REMINDER_FOX_TIME_ALL_DAY_LABEL);
					}
					else {			
						timeNode.setAttribute("label", time);
					}
				}			
			}
			else {
				dateNode.removeAttribute( "label" );
				timeNode.removeAttribute("label");
			}
			
			if ( todo.endDate != null ) {
				var monthAsText = reminderFox_getMonthAsText(todo.endDate.getMonth());		
				if ( useDefaultDate ) {
					endDateNode.setAttribute("label", monthAsText + " " + todo.endDate.getDate());
				}
				else {
					endDateNode.setAttribute("label", reminderFox_getDateVariableString( todo, todo.endDate ) );
				}	
			}
			else {
				endDateNode.removeAttribute( "label" );
			}
			
			
			
			// update description
			 todo = reminderFox_processReminderDescription(todo,  new Date().getFullYear(), true );	
			descriptionNode.setAttribute( "label", todo.summary );
			
			 // update importance
			 var isImportant = false;
			 if ( todo.priority == REMINDER_PRIORITY_IMPORTANT) { 
		         // mark the description as important (red-highlighted)
		        descriptionNode.setAttribute("properties", "important");
		        isImportant = true;
		     }
		     else {
		        descriptionNode.removeAttribute("properties");
		     }
		     
		   // update show in tooltip
		   if ( todo.completedDate != null  ) {
		    	completeNode.setAttribute("src",REMINDER_FOX_COMPLETED_TODO_IMAGE);	
		    	
		   	 	if ( isImportant ) {
		        	 descriptionNode.setAttribute("properties", "imporantCompleteText");     	
		    	 }
		    	 else {
		    	 	descriptionNode.setAttribute("properties", "completeText");     	
		    	 } 	    
		    	 
		    	 
				if ( useDefaultDate ) {
					var monthAsText = reminderFox_getMonthAsText(todo.completedDate.getMonth());		
					completedDateNode.setAttribute("label", monthAsText + " " + todo.completedDate.getDate());
				}
				else {
					completedDateNode.setAttribute("label", reminderFox_getDateVariableString( todo, todo.completedDate ) );
				} 	     	 
		    	 	
		     }
		 	else {
		   	 	if ( isImportant ) {
		        	 	//descriptionNode.setAttribute("properties", "imporantCompleteText");     	
		        	 	             // mark the date and description as important (red-highlighted)
		            //dateNode.setAttribute("properties", "important");
		    	 }
		    	 else {
		    	 	descriptionNode.removeAttribute( "properties" );  // completed setatus?
		    	 } 			 	
				completeNode.removeAttribute("src");
				completedDateNode.removeAttribute("label");
			}         
		   
		   // update show in tooltip   
		   if ( todo.showInTooltip ) {
		    	 showInTooltipNode.setAttribute("src", REMINDER_FOX_SHOW_IN_TOOLTIP_IMAGE);		 
		     }
		 	else {
				showInTooltipNode.removeAttribute("src");
			}    
		
		   if ( todo.notes != null  ) {
		    	 notesNode.setAttribute("src",REMINDER_FOX_NOTES_IMAGE);	
		     }
		 	else {
				notesNode.removeAttribute("src");
			}    	
		
			if ( todo.alarm != null ) {
				if ( todo.snoozeTime != null && todo.completedDate == null  ) { 
					alarmNode.setAttribute("src",REMINDER_FOX_ALARM_SNOOZE_IMAGE);		
				}
				else {
		 			alarmNode.setAttribute("src",REMINDER_FOX_ALARM_IMAGE);			
				}				 
		     }
		 	else {
				alarmNode.removeAttribute("src");
			}    	
			
			if ( todo.categories != null ) {
     			categoryNode.setAttribute("label", todo.categories);
			}
			else {
				categoryNode.removeAttribute("label");				
			}
				
		  	if ( mailNode != null ) {
				if (reminderFox_isMailEvent(todo) ) {
		 		   mailNode.setAttribute("src", REMINDER_FOX_MAIL_IMAGE);	
		  		}		        
				else {
					mailNode.removeAttribute("src");
				}
		  	}
		  	break;   		
		}
	}
		
	if ( modified ) {
		modifiedReminders();	
	}
	return modified;
		
}

function refreshCalendar( keepReminderArray, keepTodoArray ) {
	if ( !keepReminderArray ) { 
		calendarReminderArray = null;	
	}
	if ( !keepTodoArray) {
		calendarTodoArray = null;
	}
	oeDatePicker.redrawDays();
}


function toggleTodoShowInTooltip() {
	var selectedTodos = getAllSelectedTodos();
	for ( var i = 0; i < selectedTodos.length; i++ ) {		
		var currentTodo = selectedTodos[i];	
		currentTodo.showInTooltip = !currentTodo.showInTooltip;
		var modified = updateTodoInList( currentTodo );
	}
	modifiedReminders();
}

function toggleRemindUntilCompleted() {
	var selectedReminders = getAllSelectedReminders();
	for ( var i = 0; i < selectedReminders.length; i++ ) {		
		var currentReminder = selectedReminders[i];		
		var cleanUpReminderInList = false;

//gW_RecurringEvents 2009-02-27 	// NON recurring events are handled here 
	if (currentReminder.recurrence.type == null) {
		if ( currentReminder.remindUntilCompleted == REMINDERFOX_REMIND_UNTIL_COMPLETE_NONE ) {	
			var todaysDate = new Date();
			if (reminderFox_compareDates( currentReminder.date, todaysDate ) == -1) { // -1: date is in the past
				currentReminder.remindUntilCompleted = REMINDERFOX_REMIND_UNTIL_COMPLETE_MARKED;
				cleanUpReminderInList = true;
			} else {
				currentReminder.remindUntilCompleted = REMINDERFOX_REMIND_UNTIL_COMPLETE_TO_BE_MARKED;
			}
		}
		else if (( currentReminder.remindUntilCompleted == REMINDERFOX_REMIND_UNTIL_COMPLETE_TO_BE_MARKED ) 
			||  ( currentReminder.remindUntilCompleted == REMINDERFOX_REMIND_UNTIL_COMPLETE_MARKED)) {
			currentReminder.remindUntilCompleted = REMINDERFOX_REMIND_UNTIL_COMPLETE_NONE;
			cleanUpReminderInList = true;
		}
	} else {//  recurring events are handled here 
	
		if ( currentReminder.remindUntilCompleted == REMINDERFOX_REMIND_UNTIL_COMPLETE_NONE ) {
			currentReminder.remindUntilCompleted = REMINDERFOX_REMIND_UNTIL_COMPLETE_TO_BE_MARKED;
		}
		else if ( currentReminder.remindUntilCompleted == REMINDERFOX_REMIND_UNTIL_COMPLETE_TO_BE_MARKED ) {
			currentReminder.remindUntilCompleted = REMINDERFOX_REMIND_UNTIL_COMPLETE_NONE;
		}
		else 	if ( currentReminder.remindUntilCompleted == REMINDERFOX_REMIND_UNTIL_COMPLETE_MARKED ) {
			currentReminder.remindUntilCompleted = REMINDERFOX_REMIND_UNTIL_COMPLETE_NONE;
			cleanUpReminderInList = true;
		}
	}		
		var modified = updateReminderInList( currentReminder );
	
		modifiedReminders();
		
		// if is was marked as RemindUntilCompleted and was showing in the list at a later date, we  need to remove this from the
		// UI list back to its original location
		if ( cleanUpReminderInList ) {
			removeListItemsForReminder(currentReminder);
			createListItem(currentReminder	);
		}
	}
	
	refreshCalendar(false, true);
}


function toggleMarkAsComplete() {	 
	var selectedReminders = new Array();
	var treeChildren = document.getElementById("treechildren");
	var selectedIDsHash = {};
	
	var start = new Object();
	var end = new Object();
	var numRanges =  document.getElementById("reminderTree").view.selection.getRangeCount();
	
	for (var t = 0; t < numRanges; t++){
	  document.getElementById("reminderTree").view.selection.getRangeAt(t,start,end);
	  for (var v = start.value; v <= end.value; v++){
	    var selectedTreeItem = treeChildren.childNodes[v];
	    	
	    var reminderRefId = selectedTreeItem.childNodes[0].getAttribute(REMINDER_ID_REF);
		var currentReminder = reminderFox_getRemindersById( reminderRefId, getCurrentReminderList() );	
	   	if ( currentReminder != null ) {
			var reminderDateTime = selectedTreeItem.childNodes[0].getAttribute(REMINDER_DATE_REF);	
			var reminderInstanceDate = new Date(parseInt(reminderDateTime));		
			if ( reminderFox_isCompletedForDate( currentReminder, reminderInstanceDate ) )  {
				currentReminder.completedDate = null;																							
			}
			else {	 
				 var todaysDate = new Date();
				  // if it's a one time reminder just use today's date		
				 if ( currentReminder.recurrence.type  == REMINDER_RECURRENCE_ONETIME ) { 
				 	 currentReminder.completedDate = todaysDate;				 	
				 }
				 else { 
					 var compare = reminderFox_compareDates( reminderInstanceDate, todaysDate );					
					 if ( compare >= 0 ) {  // if reminder is today or in the future, just use that instance date
					 	currentReminder.completedDate = reminderInstanceDate;	
					 }
					 else { 	
							// if we mark a repeating guy as complete and the next instance is in the future, then use today's date as the complete
							// date, and not the occurrence. 
							var currentInstanceDate = new Date( reminderInstanceDate.getFullYear(), reminderInstanceDate.getMonth(), reminderInstanceDate.getDate(), 
								reminderInstanceDate.getHours(), reminderInstanceDate.getMinutes() );
							currentInstanceDate.setDate( currentInstanceDate.getDate() + 1);
							var nextReminderInstance = reminderFox_getFirstReminderOccurrenceAfterStartDate( currentReminder, currentInstanceDate );						
							var compare = reminderFox_compareDates( nextReminderInstance.date, todaysDate );
							if ( compare == 1 ) { // if today's date is greater than instance, use today
								currentReminder.completedDate = todaysDate;						
							}
							else {
								// if today's date is less than or equal to the reminder instance's date, then use the reminder's date
								currentReminder.completedDate = reminderInstanceDate;	
							}							
					 }
				 }
				 								
				//gW TAG  2008-12-14    do we really want to delete the TAG with 'COMPLETE' ??
				// need to clear Mail label if a message is attached to this reminder
				/** ----------
				if ( currentReminder.messageID != null ) {		
					if ( window.arguments != null ) {				
						var clearMailLabelCallback = window.arguments[1].clearMailLabelCallback;
						if ( clearMailLabelCallback != null ) {				
							clearMailLabelCallback(  currentReminder.messageID );
						}
					}
				}	----------- **/
				
				
			

				// if reminder is marked as Remind Until Complete, clear it (if one-time, clear the RUC completely;
				// if a repeating reminder, simply change back to RUC-marked)  and update the reminder
				//  in the list (as the current reminder instance may be removed)
				if (  currentReminder.recurrence.type  == REMINDER_RECURRENCE_ONETIME && 
					( currentReminder.remindUntilCompleted == REMINDERFOX_REMIND_UNTIL_COMPLETE_TO_BE_MARKED ||
					  currentReminder.remindUntilCompleted == REMINDERFOX_REMIND_UNTIL_COMPLETE_MARKED )  ) {
					selectCalendarSync = false;
		     		toggleRemindUntilCompleted(); 
		     		modifiedReminders();
		     		selectCalendarSync = true;  
		     		return;  	
				}	
				else if ( currentReminder.remindUntilCompleted == REMINDERFOX_REMIND_UNTIL_COMPLETE_MARKED ) {
				    selectCalendarSync = false;
					currentReminder.remindUntilCompleted = REMINDERFOX_REMIND_UNTIL_COMPLETE_TO_BE_MARKED;
					var modified = updateReminderInList( currentReminder );
					modifiedReminders();
					
					// if is was marked as RemindUntilCompleted and was showing in the list at a later date, we  need to remove this from the
					// UI list back to its original location
					removeListItemsForReminder(currentReminder);
					createListItem(currentReminder	);
					selectCalendarSync = true;  
					return;
				}		
			}					
	
			var modified = updateReminderInList( currentReminder );					
			sortReminderIfNeccessary( currentReminder.id);
		}			
	  }
	}	
	
	refreshCalendar(false, true);
	modifiedReminders();
	
	
}

function toggleTodoMarkAsComplete() {
	var selectedTodos = getAllSelectedTodos();
	for ( var i = 0; i < selectedTodos.length; i++ ) {		
		var currentTodo = selectedTodos[i];
			if ( currentTodo.completedDate != null ) { 
				currentTodo.completedDate = null;
			}
			else {
				currentTodo.completedDate = new Date();;
			}
			var modified = updateTodoInList( currentTodo );
			
			sortTodoIfNeccessary( currentTodo.id);
	}
	refreshCalendar(true, false);
	modifiedReminders();
}

function revertActions() {
	// I don't know how to refresh Reminders and Todos
	var revertReminders = true;
	var revertTodos = true;

	reminderFox_clearRemindersAndTodos();
	removeAllListItems(revertReminders, revertTodos);
	calendarReminderArray = null;  // null out in case reminder columns are sorted
	calendarTodoArray = null;
	fillList(revertReminders, revertTodos);
	refreshCalendar();

	// grey out the rever buttons
	var revertButton= document.getElementById("revertbutton");
	revertButton.setAttribute( "disabled", true );
	
	var revertButtonTodos= document.getElementById("revertbuttonTodos");
	revertButtonTodos.setAttribute( "disabled", true );
	
	g_modified = false;
}

function reminderFox_doFocusQuickSearch() {
	var desc = document.getElementById("rmSearchText");
	desc.focus();
}

function refillLists() {
	rmFx_View.SetTitel();
		
	var revertReminders;
	var revertTodos;
	
	if (isReminderTabSelected() ) {
		revertReminders = true;
		revertTodos = false;
	}
	else {
		revertReminders = false;
		revertTodos = true;		
	}
 
	removeAllListItems(revertReminders, revertTodos);
	fillList(revertReminders, revertTodos);
	refreshCalendar();
}




 function sortcolumn(column) { 
 	var name  = column.getAttribute("id");
 	
 	// get current tab name....	
	var tabList = document.getElementById("tabList");	
	var tab =	tabList.selectedItem;
	var tabName = tab.getAttribute( "label");
	// get hashmap - check for tabname	
	var sortInfo = listSortMap[tabName];
	if ( sortInfo == null ) {
		// if not there -= then set this tabname-->{column, 0} (ascending)
		listSortMap[tabName] = { sortColumn: name, sortDirection:  REMINDER_FOX_SORT_DIRECTION_ASCENDING };
	}
	else {
		if ( sortInfo.sortColumn == name ) {	
			// same column -- increase sortDir
			if ( sortInfo.sortDirection == REMINDER_FOX_SORT_DIRECTION_ASCENDING ) {
				listSortMap[tabName] = { sortColumn: name, sortDirection:  REMINDER_FOX_SORT_DIRECTION_DESCENDING};
			}
			else {
				//  if desc--> then increase and REMOVE entry
				listSortMap[tabName] = null;
			}
		}
		else {
			// new column
			listSortMap[tabName] = { sortColumn: name, sortDirection:  REMINDER_FOX_SORT_DIRECTION_ASCENDING };
		}
	}

	if ( isReminderTabSelected() ) {
 		removeAllListItems( true, false );
		fillList( true, false);
	}
	else {
		removeAllListItems( false, true );
		fillList( false, true );
	}
	
	modifiedReminders();
 }
 
 
 function isTabSorted() {
 	var tabList = document.getElementById("tabList");	
	var tab =	tabList.selectedItem;
	var tabName = tab.getAttribute( "label");
	// get hashmap - check for tabname	
	var sortInfo = listSortMap[tabName];
	if ( sortInfo != null ) {
		//reminderFox_logMessageLevel("SortInfo: " + sortInfo.sortColumn + " -> " + sortInfo.sortDirection, REMINDER_FOX_LOG_LEVEL_DEBUG);
		return true;
	}
	else {
		return false;
	}
 }
 
 function isTodoTabSorted() {
 	var tabList = document.getElementById("tabList");	
	var tab =	tabList.childNodes[1];
	var tabName = tab.getAttribute( "label");
	
	// get hashmap - check for tabname	
	var sortInfo = listSortMap[tabName];
	if ( sortInfo != null ) {
		return true;
	}
	else {
		return false;
	}
 }
 
 function fillListSortTodos() {
 	var tabList = document.getElementById("tabList");	
	var tab =	tabList.selectedItem;
	var tabName = tab.getAttribute( "label");
 	
 	clearAllSortColumns(); 
	 if (  listSortMap[tabName].sortDirection == REMINDER_FOX_SORT_DIRECTION_ASCENDING) {
 		var column = document.getElementById(listSortMap[tabName].sortColumn );		
 		column.setAttribute("sortDirection", "ascending");		 		
 	}
 	else { 		
 		var column = document.getElementById(listSortMap[tabName].sortColumn );		
 		column.setAttribute("sortDirection", "descending");		
 	} 	
 	
 	
 	var todos = getCurrentTodoList();
		
	var sortedArray;
	var unsortedArray = new Array();
	var displayList = document.getElementById("displayTypeTodo");			
	if ( displayList != null && displayList.selectedIndex > 0 ) {
		var todaysDate = new Date();
		var monthArray, dayReminderArray;
		var monthIndex, dayIndex, reminderIndex;
		for ( monthIndex = 0; monthIndex < 12; monthIndex++ ) {
			monthArray = calendarTodoArray[monthIndex];
			if ( monthArray != null ) {
				for ( dayIndex = 0; dayIndex < 31; dayIndex++ ) {
					dayReminderArray = monthArray[dayIndex];
					if ( dayReminderArray != null ) {
						for ( reminderIndex = 0; reminderIndex < dayReminderArray.length; reminderIndex++ ) {
							unsortedArray[unsortedArray.length] = dayReminderArray[reminderIndex];
						}
					}
				}
			}
		}	
		
		sortedArray = new Array( unsortedArray.length );
		for ( var i = 0; i < unsortedArray.length; i++ ) {
			sortedArray[i] = unsortedArray[i];
			sortedArray[i].originalIndex = i;
		}				 
	}
	else {
		var sortedArray = new Array( todos.length );
		for ( var i = 0; i < todos.length; i++ ) {
			sortedArray[i] = todos[i];
			sortedArray[i].originalIndex = i;
		}
	}
		
	reminderFox_quick_sort( sortedArray, listSortMap[tabName].sortColumn, listSortMap[tabName].sortDirection );
			
	removeAllListItems( false, true );
	
	var todaysDate = new Date();
	 for( i = 0; i < sortedArray.length; i++) {
		createTodoListItem(sortedArray[i], false, todaysDate, false);
	}
	highlightTodo();
		
   	selectNewReminderText();
 }
 
 
 function fillListSortReminders( ignoreHighlight ) {
 	var tabList = document.getElementById("tabList");	
	var tab =	tabList.selectedItem;
	var tabName = tab.getAttribute( "label");
 	
	clearAllSortColumns();
	 if (  listSortMap[tabName].sortDirection == REMINDER_FOX_SORT_DIRECTION_ASCENDING) {
 		var column = document.getElementById(listSortMap[tabName].sortColumn );		
 		column.setAttribute("sortDirection", "ascending");		 		
 	}
 	else { 		
 		var column = document.getElementById(listSortMap[tabName].sortColumn );		
 		column.setAttribute("sortDirection", "descending");		
 	} 	 	
 	
	removeAllListItems( true, false );
	if ( calendarReminderArray == null ) {
		createCalendarReminderArray();		
	}
	var unsortedArray = new Array();
	var monthArray, dayReminderArray;
	var monthIndex, dayIndex, reminderIndex;
	for ( monthIndex = 0; monthIndex < 12; monthIndex++ ) {
		monthArray = calendarReminderArray[monthIndex];
		if ( monthArray != null ) {
			for ( dayIndex = 0; dayIndex < 31; dayIndex++ ) {
				dayReminderArray = monthArray[dayIndex];
				if ( dayReminderArray != null ) {
					for ( reminderIndex = 0; reminderIndex < dayReminderArray.length; reminderIndex++ ) {
						//createListItemSorted(dayReminderArray[reminderIndex]);
						unsortedArray[unsortedArray.length] = dayReminderArray[reminderIndex];
					}
				}
			}
		}
	}
	
	
	var sortedArray = new Array( unsortedArray.length );
	for ( var i = 0; i < unsortedArray.length; i++ ) {
		sortedArray[i] = unsortedArray[i];
		sortedArray[i].originalIndex = i;
	}		
	
	var todaysDate = new Date();
	reminderFox_quick_sort( sortedArray, listSortMap[tabName].sortColumn, listSortMap[tabName].sortDirection );
	 for( i = 0; i < sortedArray.length; i++) {
		createListItemSorted(sortedArray[i], todaysDate);
	}
	
	if ( !ignoreHighlight ) {
		// now that we've added the sorted reminders in the list, let's
		// select (highlight) today's reminder or the next upcoming reminder
		highlightClosestUpcomingReminder( new Date());			
	}
 }
 
 function clearAllSortColumns() {
 	// clear reminder columns
	if ( isReminderTabSelected() ) {
		document.getElementById("dateColLabel").removeAttribute("sortDirection");		
		document.getElementById("descColLabel").removeAttribute("sortDirection");		
		document.getElementById("timeColLabel").removeAttribute("sortDirection");		
		document.getElementById("dateCompleted").removeAttribute("sortDirection");		
		document.getElementById("repeatColLabel").removeAttribute("sortDirection");		
		document.getElementById("CompleteColLabel").removeAttribute("sortDirection");		
		document.getElementById("remindUntilCompletedColLabel").removeAttribute("sortDirection");		
		document.getElementById("notesColLabel").removeAttribute("sortDirection");		
		document.getElementById("alarmColLabel").removeAttribute("sortDirection");		
		document.getElementById("mailColLabel").removeAttribute("sortDirection");
		document.getElementById("catColLabel").removeAttribute("sortDirection");		
		document.getElementById("endDateColLabel").removeAttribute("sortDirection");								
	}
	else {
		// clear todo columns
		document.getElementById("todoDateColLabel").removeAttribute("sortDirection");		
		document.getElementById("todoDescColLabel").removeAttribute("sortDirection");		
		document.getElementById("todoDateCompleted").removeAttribute("sortDirection");		
		document.getElementById("todoCompleteColLabel").removeAttribute("sortDirection");		
		document.getElementById("todoShowInTooltip").removeAttribute("sortDirection");		
		document.getElementById("todoTimeColLabel").removeAttribute("sortDirection");		
		document.getElementById("todoAlarmColLabel").removeAttribute("sortDirection");		
		document.getElementById("todoNotesColLabel").removeAttribute("sortDirection");		
		document.getElementById("todoMailColLabel").removeAttribute("sortDirection");					
		document.getElementById("todocatColLabel").removeAttribute("sortDirection");
		document.getElementById("todoEndDateColLabel").removeAttribute("sortDirection");				
	}

 }
 
 
function sortTodoIfNeccessary(todoID) {
	if ( isTabSorted() ) {
		removeAllListItems( false, true );
		fillList( false, true);			
	}  		
	
	
	var todoName;
	var tabList = document.getElementById("tabList");	
	var tab =	tabList.selectedItem;
	var tabIndex =	tabList.selectedIndex;
	var index = tab.id.indexOf( ':' );
	if ( tabIndex <= 1 || index == -1 ) {
		todoName = REMINDER_FOX_DEFAULT_TODOS_CATEGORY;
	}
	else {
		todoName = tab.id.substring( index +1 , tab.id.length );
	}
	selectTodoById(todoName, todoID );
}

function sortReminderIfNeccessary(reminderID) {
	if ( isTabSorted() ) {
		removeAllListItems( true, false );
		calendarReminderArray = null;
		fillList( true, false);			
		selectReminderById(reminderID);
	}  			
}

function displayTypeChanged() {
	calendarReminderArray = null;  // null out in case reminder columns are sorted
	refillLists();  
}

function displayTypeChangedTodo() {
	calendarTodoArray = null;
	refillLists(); 
}

function getDisplayIndex(isRemindersOrTodosString) {
	var displayList;
	var displayListIndex = -1;
	if ( isRemindersOrTodosString == "reminders" || (isRemindersOrTodosString != "todos" && isReminderTabSelected()) ) { 
		displayList = document.getElementById("displayType"); // part of "rmFilterHbox"/"rmFilterText"
	}
	else {
		displayList = document.getElementById("displayTypeTodo");
	}	
	if ( displayList != null ) {	
		displayListIndex = displayList.selectedIndex;
	}
	return displayListIndex;
}


function getCurrentTodoListOrALL() {
   var todosArr = reminderFox_getReminderTodos();
   var tabList = document.getElementById("tabList");  
   var tab =   tabList.selectedItem;
   var tabIndex = tabList.selectedIndex;
   
   if (tab.label != "&ALLTODO") {
	   var index = tab.id.indexOf( ':' );
	   if ( tabIndex <= 1 || index == -1 ) {
	      name = REMINDER_FOX_DEFAULT_TODOS_CATEGORY;
	   }
	   else {
	      name = tab.id.substring( index +1 , tab.id.length );
	   }
	   var todos = todosArr[name];
	   if ( todos == null ) {
	      todos = new Array();
	      todosArr[name] = todos;
	   }
	   return todos;
   } 
   else {
   	
   	// this is a test to get all Todo's/Lists into ONE todo list named "&ALLTODO"
   	var cArray = new Array();
   	for (var indexList = 1; indexList < tabList.children.length; indexList++ ) {
   		tab = tabList.children[indexList];
   		index = tab.id.indexOf( ':' );
   		if (indexList == 1) {
   			iName = "ToDo's";       //gwTodo  ???? always this name (locale ???)
   		} else {
   		 iName = tab.id.substring( index +1 , tab.id.length );
   		}
   		if (iName != "&ALLTODO") {
   		  var cLen = cArray.length;
   		  for (var indexSub = 0; indexSub <todosArr[iName].length; indexSub++) {
   		  	   cArray[cLen] = todosArr[iName][indexSub];
   		  	   cLen++;
   		  }		  
   		}
   	}
    	return cArray;
   }
   
}